<template>
  <div class="trading-container">
    <el-row :gutter="20">
      <!-- 市场概览 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>市场概览</span>
              <div class="data-source-controls">
                <span class="last-updated">最后更新: {{ lastUpdated }}</span>
                <el-select v-model="selectedDataSource" placeholder="选择数据源" size="small" style="margin-right: 10px;">
                  <el-option
                    v-for="item in dataSources"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-button type="primary" size="small" @click="fetchDataBySource" :loading="isLoading">刷新</el-button>
                <el-switch
                  v-model="autoRefresh"
                  active-text="自动刷新"
                  inactive-text="手动刷新"
                  @change="toggleAutoRefresh"
                />
              </div>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6" v-for="(item, index) in marketOverview" :key="index">
              <div class="market-item" :class="{ 'up': item.change > 0, 'down': item.change < 0 }">
                <div class="market-name">{{ item.name }}</div>
                <div class="market-price">{{ item.price }}</div>
                <div class="market-change">
                  <span>{{ item.change > 0 ? '+' : '' }}{{ item.change }}%</span>
                  <el-icon v-if="item.change > 0"><CaretTop /></el-icon>
                  <el-icon v-else-if="item.change < 0"><CaretBottom /></el-icon>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 多数据源比较 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>多数据源价格比较</span>
              <div>
                <el-tag type="success">每分钟自动更新所有数据源</el-tag>
                <el-button type="primary" size="small" @click="fetchAllDataSources" :loading="isLoading" style="margin-left: 10px;">立即刷新全部</el-button>
              </div>
            </div>
          </template>
          <el-table :data="comparisonData" style="width: 100%" border>
            <el-table-column prop="symbol" label="交易对" width="120"></el-table-column>
            <el-table-column label="CoinGecko">
              <template #default="scope">
                <div class="price-cell">
                  <div>{{ scope.row.coingecko.price || '加载中...' }}</div>
                  <div :class="{ 'up': scope.row.coingecko.change > 0, 'down': scope.row.coingecko.change < 0 }">
                    {{ scope.row.coingecko.change > 0 ? '+' : '' }}{{ scope.row.coingecko.change }}%
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="Binance">
              <template #default="scope">
                <div class="price-cell">
                  <div>{{ scope.row.binance.price || '加载中...' }}</div>
                  <div :class="{ 'up': scope.row.binance.change > 0, 'down': scope.row.binance.change < 0 }">
                    {{ scope.row.binance.change > 0 ? '+' : '' }}{{ scope.row.binance.change }}%
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="CryptoCompare">
              <template #default="scope">
                <div class="price-cell">
                  <div>{{ scope.row.cryptocompare.price || '加载中...' }}</div>
                  <div :class="{ 'up': scope.row.cryptocompare.change > 0, 'down': scope.row.cryptocompare.change < 0 }">
                    {{ scope.row.cryptocompare.change > 0 ? '+' : '' }}{{ scope.row.cryptocompare.change }}%
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格差异">
              <template #default="scope">
                <div class="price-diff">
                  <el-tooltip content="最高价与最低价之间的差异百分比" placement="top">
                    <span :class="{ 'warning': scope.row.priceDiff > 1 }">
                      {{ scope.row.priceDiff.toFixed(2) }}%
                    </span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- Binance 交易图表 - 单独占一行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>Binance 交易图表</span>
              <div style="display: flex; align-items: center; gap: 10px;">
                <!-- 实时价格显示 -->
                <div v-if="binanceCurrentPrice > 0" style="display: flex; align-items: center; gap: 8px;">
                  <el-icon color="#1890ff" size="16"><Connection /></el-icon>
                  <span style="font-size: 12px; color: #666;">实时价格:</span>
                  <el-tag type="success" size="small" style="font-weight: bold;">
                    ${{ binanceCurrentPrice.toLocaleString() }}
                  </el-tag>
                </div>
                <el-select v-model="binanceSymbol" placeholder="选择交易对" size="small" @change="updateBinanceChart">
                  <el-option
                    v-for="item in symbols"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value.replace('/', '')">
                  </el-option>
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <webview 
              ref="binanceWebview"
              :src="`https://www.binance.com/zh-CN/trade/${binanceSymbol}?theme=dark&type=spot`"
              class="binance-webview"
              allowpopups
              allow="autoplay; fullscreen"
              webpreferences="contextIsolation=no"
            ></webview>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搬砖套利监控 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>搬砖套利监控</span>
              <div style="display: flex; align-items: center; gap: 10px;">
                <el-select v-model="arbitrageSymbol" placeholder="选择交易对" size="small" @change="updateArbitrageData">
                  <el-option
                    v-for="item in symbols"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-button type="primary" size="small" @click="startArbitrageMonitoring" :loading="isArbitrageMonitoring">
                  {{ isArbitrageMonitoring ? '停止监控' : '开始监控' }}
                </el-button>
                <el-tag v-if="arbitrageOpportunity && arbitrageOpportunity.spread !== undefined" type="success" size="small">
                  发现套利机会！价差: {{ arbitrageOpportunity.spread !== undefined ? arbitrageOpportunity.spread.toFixed(2) : '0.00' }}%
                </el-tag>
                <!-- 导出按钮 -->
                <el-button 
                  type="success" 
                  size="small" 
                  @click="exportArbitrageHistory"
                  :disabled="!arbitrageHistory || arbitrageHistory.length === 0"
                >
                  导出记录
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 套利参数设置 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="param-setting">
                  <div class="param-title">套利阈值</div>
                  <el-slider 
                    v-model="arbitrageThreshold" 
                    :min="0.1" 
                    :max="5" 
                    :step="0.1" 
                    show-input
                    show-input-controls="false"
                  ></el-slider>
                  <div class="param-desc">当价差超过此值时触发套利提醒</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="param-setting">
                  <div class="param-title">交易数量</div>
                  <el-input-number 
                    v-model="tradeAmount" 
                    :min="0.001" 
                    :step="0.1" 
                    size="small"
                  ></el-input-number>
                  <div class="param-desc">每次套利交易的数量</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="param-setting">
                  <div class="param-title">更新频率</div>
                  <el-select v-model="arbitrageUpdateInterval" size="small" @change="changeUpdateInterval">
                    <el-option label="5秒" :value="5000"></el-option>
                    <el-option label="10秒" :value="10000"></el-option>
                    <el-option label="30秒" :value="30000"></el-option>
                    <el-option label="1分钟" :value="60000"></el-option>
                  </el-select>
                  <div class="param-desc">数据更新的时间间隔</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <div class="param-setting">
                  <div class="param-title">手续费率</div>
                  <el-input-number 
                    v-model="arbitrageFeeRate" 
                    :min="0.0001" 
                    :max="0.01" 
                    :step="0.0001" 
                    size="small"
                    :precision="4"
                  ></el-input-number>
                  <div class="param-desc">交易所手续费率(默认0.1%)</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 套利统计信息 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="4">
              <el-card class="stat-card">
                <div class="stat-title">总套利次数</div>
                <div class="stat-number">{{ arbitrageStats.totalOpportunities !== undefined ? arbitrageStats.totalOpportunities : 0 }}</div>
              </el-card>
            </el-col>
            <el-col :span="4">
              <el-card class="stat-card">
                <div class="stat-title">成功套利</div>
                <div class="stat-number" :class="{ 'up': arbitrageStats.successfulTrades > 0 }">
                  {{ arbitrageStats.successfulTrades !== undefined ? arbitrageStats.successfulTrades : 0 }}
                </div>
              </el-card>
            </el-col>
            <el-col :span="4">
              <el-card class="stat-card">
                <div class="stat-title">总利润</div>
                <div class="stat-number" :class="{ 'up': arbitrageStats.totalProfit > 0, 'down': arbitrageStats.totalProfit < 0 }">
                  ${{ arbitrageStats.totalProfit !== undefined ? arbitrageStats.totalProfit.toFixed(2) : '0.00' }}
                </div>
              </el-card>
            </el-col>
            <el-col :span="4">
              <el-card class="stat-card">
                <div class="stat-title">平均价差</div>
                <div class="stat-number">{{ arbitrageStats.avgSpread !== undefined ? arbitrageStats.avgSpread.toFixed(2) : '0.00' }}%</div>
              </el-card>
            </el-col>
            <el-col :span="4">
              <el-card class="stat-card">
                <div class="stat-title">最大价差</div>
                <div class="stat-number up">{{ arbitrageStats.maxSpread !== undefined ? arbitrageStats.maxSpread.toFixed(2) : '0.00' }}%</div>
              </el-card>
            </el-col>
            <el-col :span="4">
              <el-card class="stat-card">
                <div class="stat-title">成功率</div>
                <div class="stat-number" :class="{ 'up': arbitrageStats.successRate > 50, 'down': arbitrageStats.successRate < 30 }">
                  {{ arbitrageStats.successRate !== undefined ? arbitrageStats.successRate.toFixed(1) : '0.0' }}%
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 监控时长 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="24">
              <el-card class="stat-card">
                <div class="stat-title">监控时长</div>
                <div class="stat-number">{{ formatDuration(arbitrageStats.monitoringTime) }}</div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 套利机会通知区域 -->
          <el-row :gutter="20" style="margin-bottom: 20px;" v-if="arbitrageOpportunity">
            <el-col :span="24">
              <el-alert
                :title="`套利机会发现：${arbitrageSymbol} 价差 ${arbitrageOpportunity.spread !== undefined ? arbitrageOpportunity.spread.toFixed(2) : '0.00'}%`"
                :description="`Binance价格: $${arbitrageOpportunity.binancePrice !== undefined ? arbitrageOpportunity.binancePrice.toLocaleString() : '0'} | OKX价格: $${arbitrageOpportunity.okxPrice !== undefined ? arbitrageOpportunity.okxPrice.toLocaleString() : '0'} | 预计利润: $${arbitrageOpportunity.profit !== undefined ? arbitrageOpportunity.profit.toFixed(2) : '0.00'}`"
                type="success"
                show-icon
                :closable="false"
              >
              </el-alert>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card shadow="hover">
                <div class="exchange-card">
                  <div class="exchange-header">
                    <h3>Binance</h3>
                    <el-tag type="primary">买入</el-tag>
                  </div>
                  <div class="exchange-price">{{ binanceArbitragePrice !== undefined ? binanceArbitragePrice.toLocaleString() : '0' }}</div>
                  <div class="exchange-change" :class="{ 'up': binanceChange > 0, 'down': binanceChange < 0 }">
                    {{ binanceChange !== undefined ? (binanceChange > 0 ? '+' : '') + binanceChange.toFixed(2) : '0.00' }}%
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <el-col :span="8">
              <el-card shadow="hover">
                <div class="exchange-card">
                  <div class="exchange-header">
                    <h3>OKX</h3>
                    <el-tag type="danger">卖出</el-tag>
                  </div>
                  <div class="exchange-price">{{ okxArbitragePrice !== undefined ? okxArbitragePrice.toLocaleString() : '0' }}</div>
                  <div class="exchange-change" :class="{ 'up': okxChange > 0, 'down': okxChange < 0 }">
                    {{ okxChange !== undefined ? (okxChange > 0 ? '+' : '') + okxChange.toFixed(2) : '0.00' }}%
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <el-col :span="8">
              <el-card shadow="hover">
                <div class="exchange-card">
                  <div class="exchange-header">
                    <h3>套利信息</h3>
                  </div>
                  <div class="arbitrage-info">
                    <div class="arbitrage-spread">价差: {{ arbitrageSpread !== undefined ? arbitrageSpread.toFixed(2) : '0.00' }}%</div>
                    <div class="arbitrage-value">套利价值: ${{ arbitrageValue !== undefined ? arbitrageValue.toFixed(2) : '0.00' }}</div>
                    <div class="arbitrage-fee">预估手续费: ${{ arbitrageFee !== undefined ? arbitrageFee.toFixed(2) : '0.00' }}</div>
                    <div class="arbitrage-profit" :class="{ 'profit': (arbitrageValue - arbitrageFee) > 0, 'loss': (arbitrageValue - arbitrageFee) <= 0 }">
                      预估利润: ${{ (arbitrageValue !== undefined && arbitrageFee !== undefined) ? (arbitrageValue - arbitrageFee).toFixed(2) : '0.00' }}
                    </div>
                    <div class="arbitrage-timer" v-if="isArbitrageMonitoring">
                      监控时长: {{ formatDuration(arbitrageStats.monitoringTime) }}
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 套利历史记录 -->
          <el-table :data="arbitrageHistory" style="width: 100%; margin-top: 20px;" border>
            <el-table-column prop="time" label="时间" width="180"></el-table-column>
            <el-table-column prop="symbol" label="交易对" width="120"></el-table-column>
            <el-table-column prop="binancePrice" label="Binance价格">
              <template #default="scope">
                ${{ scope.row.binancePrice !== undefined ? scope.row.binancePrice.toLocaleString() : '0' }}
              </template>
            </el-table-column>
            <el-table-column prop="okxPrice" label="OKX价格">
              <template #default="scope">
                ${{ scope.row.okxPrice !== undefined ? scope.row.okxPrice.toLocaleString() : '0' }}
              </template>
            </el-table-column>
            <el-table-column prop="spread" label="价差%">
              <template #default="scope">
                <span :class="scope.row.spread > 0 ? 'up' : 'down'">
                  {{ scope.row.spread !== undefined ? scope.row.spread.toFixed(2) : '0.00' }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="profit" label="预估利润">
              <template #default="scope">
                <span :class="scope.row.profit > 0 ? 'up' : 'down'">
                  ${{ scope.row.profit !== undefined ? scope.row.profit.toFixed(2) : '0.00' }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- OKX 交易图表 - 单独占一行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>OKX 交易图表</span>
              <div style="display: flex; align-items: center; gap: 10px;">
                <!-- 实时价格显示 -->
                <div v-if="okxCurrentPrice > 0" style="display: flex; align-items: center; gap: 8px;">
                  <el-icon color="#1890ff" size="16"><Connection /></el-icon>
                  <span style="font-size: 12px; color: #666;">实时价格:</span>
                  <el-tag type="success" size="small" style="font-weight: bold;">
                    ${{ okxCurrentPrice.toLocaleString() }}
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <webview 
              ref="okxWebview"
              src="https://www.okx.com/zh-hans/price/bitcoin-btc"
              class="binance-webview"
              allowpopups
              allow="autoplay; fullscreen"
              webpreferences="contextIsolation=no"
            ></webview>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage, ElLoading, ElMessageBox, ElNotification } from 'element-plus'
import { 
  TrendCharts, 
  DataAnalysis, 
  Download, 
  Delete, 
  VideoPause, 
  Connection,
  Clock,
  Warning,
  CaretTop,
  CaretBottom,
  QuestionFilled
} from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'Trading',
  components: {
    TrendCharts,
    DataAnalysis,
    Download,
    Delete,
    VideoPause,
    Connection,
    Clock,
    Warning,
    CaretTop,
    CaretBottom,
    QuestionFilled
  },
  setup() {
    // 数据源选择
    const dataSources = [
      { value: 'coingecko', label: 'CoinGecko' },
      { value: 'binance', label: 'Binance' },
      { value: 'cryptocompare', label: 'CryptoCompare' }
    ]
    const selectedDataSource = ref('coingecko')
    const isLoading = ref(false)
    const lastUpdated = ref(new Date().toLocaleString())
    const autoRefresh = ref(true)
    const refreshInterval = ref(null)
    
    // 多数据源比较数据
    const comparisonData = reactive([
      { 
        symbol: 'BTC/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'ETH/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'BNB/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      },
      { 
        symbol: 'SOL/USDT',
        coingecko: { price: '', change: 0 },
        binance: { price: '', change: 0 },
        cryptocompare: { price: '', change: 0 },
        priceDiff: 0
      }
    ])
    
    // 计算价格差异
    const calculatePriceDiff = (symbol) => {
      const item = comparisonData.find(item => item.symbol === symbol)
      if (!item) return
      
      const prices = [
        parseFloat(item.coingecko.price.replace(/,/g, '')) || 0,
        parseFloat(item.binance.price.replace(/,/g, '')) || 0,
        parseFloat(item.cryptocompare.price.replace(/,/g, '')) || 0
      ].filter(price => price > 0)
      
      if (prices.length < 2) {
        item.priceDiff = 0
        return
      }
      
      const maxPrice = Math.max(...prices)
      const minPrice = Math.min(...prices)
      item.priceDiff = ((maxPrice - minPrice) / minPrice) * 100
    }
    
    // 获取所有数据源的数据
    const fetchAllDataSources = async () => {
      try {
        isLoading.value = true
        // 并行获取所有三个数据源的数据
        await Promise.all([
          fetchCoinGeckoData(false),
          fetchBinanceData(false),
          fetchCryptoCompareData(false)
        ])
        
        // 计算所有交易对的价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        lastUpdated.value = new Date().toLocaleString()
        ElMessage({
          message: '所有数据源更新成功',
          type: 'success'
        })
      } catch (error) {
        console.error('更新数据源失败:', error)
        ElMessage({
          message: '部分数据源更新失败，请稍后重试',
          type: 'warning'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 启动自动刷新
    const startAutoRefresh = () => {
      if (refreshInterval.value) clearInterval(refreshInterval.value)
      refreshInterval.value = setInterval(() => {
        fetchAllDataSources() // 每分钟刷新所有三个数据源的数据
      }, 60000) // 60秒
    }
    
    // 停止自动刷新
    const stopAutoRefresh = () => {
      if (refreshInterval.value) {
        clearInterval(refreshInterval.value)
        refreshInterval.value = null
      }
    }
    
    // 切换自动刷新状态
    const toggleAutoRefresh = () => {
      if (autoRefresh.value) {
        startAutoRefresh()
      } else {
        stopAutoRefresh()
      }
    }
    
    // 市场概览数据
    const marketOverview = reactive([
      { name: 'BTC/USDT', price: '加载中...', change: 0 },
      { name: 'ETH/USDT', price: '加载中...', change: 0 },
      { name: 'BNB/USDT', price: '加载中...', change: 0 },
      { name: 'SOL/USDT', price: '加载中...', change: 0 }
    ])
    
    // 获取CoinGecko数据
    const fetchCoinGeckoData = async (showMessage = true) => {
      try {
        isLoading.value = true
        const response = await axios.get('https://api.coingecko.com/api/v3/simple/price', {
          params: {
            ids: 'bitcoin,ethereum,binancecoin,solana',
            vs_currencies: 'usd',
            include_24hr_change: 'true'
          }
        })
        
        const data = response.data
        
        // 更新市场概览数据
        marketOverview[0].price = data.bitcoin.usd.toLocaleString()
        marketOverview[0].change = parseFloat(data.bitcoin.usd_24h_change.toFixed(2))
        
        marketOverview[1].price = data.ethereum.usd.toLocaleString()
        marketOverview[1].change = parseFloat(data.ethereum.usd_24h_change.toFixed(2))
        
        marketOverview[2].price = data.binancecoin.usd.toLocaleString()
        marketOverview[2].change = parseFloat(data.binancecoin.usd_24h_change.toFixed(2))
        
        marketOverview[3].price = data.solana.usd.toLocaleString()
        marketOverview[3].change = parseFloat(data.solana.usd_24h_change.toFixed(2))
        
        // 更新比较数据
        comparisonData[0].coingecko.price = data.bitcoin.usd.toLocaleString()
        comparisonData[0].coingecko.change = parseFloat(data.bitcoin.usd_24h_change.toFixed(2))
        
        comparisonData[1].coingecko.price = data.ethereum.usd.toLocaleString()
        comparisonData[1].coingecko.change = parseFloat(data.ethereum.usd_24h_change.toFixed(2))
        
        comparisonData[2].coingecko.price = data.binancecoin.usd.toLocaleString()
        comparisonData[2].coingecko.change = parseFloat(data.binancecoin.usd_24h_change.toFixed(2))
        
        comparisonData[3].coingecko.price = data.solana.usd.toLocaleString()
        comparisonData[3].coingecko.change = parseFloat(data.solana.usd_24h_change.toFixed(2))
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 更新K线图表数据，仅当当前选中的数据源是CoinGecko时
        if (selectedDataSource.value === 'coingecko') {
          updateChartData(data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'CoinGecko数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取CoinGecko数据失败:', error)
        ElMessage({
          message: '获取CoinGecko数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 获取Binance数据
    const fetchBinanceData = async (showMessage = true) => {
      try {
        isLoading.value = true
        
        // 并行请求多个交易对数据
        const [btcResponse, ethResponse, bnbResponse, solResponse] = await Promise.all([
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=ETHUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=BNBUSDT'),
          axios.get('https://api.binance.com/api/v3/ticker/24hr?symbol=SOLUSDT')
        ])
        
        // 更新市场概览数据
        marketOverview[0].price = parseFloat(btcResponse.data.lastPrice).toLocaleString()
        marketOverview[0].change = parseFloat(btcResponse.data.priceChangePercent)
        
        marketOverview[1].price = parseFloat(ethResponse.data.lastPrice).toLocaleString()
        marketOverview[1].change = parseFloat(ethResponse.data.priceChangePercent)
        
        marketOverview[2].price = parseFloat(bnbResponse.data.lastPrice).toLocaleString()
        marketOverview[2].change = parseFloat(bnbResponse.data.priceChangePercent)
        
        marketOverview[3].price = parseFloat(solResponse.data.lastPrice).toLocaleString()
        marketOverview[3].change = parseFloat(solResponse.data.priceChangePercent)
        
        // 更新比较数据
        comparisonData[0].binance.price = parseFloat(btcResponse.data.lastPrice).toLocaleString()
        comparisonData[0].binance.change = parseFloat(btcResponse.data.priceChangePercent)
        
        comparisonData[1].binance.price = parseFloat(ethResponse.data.lastPrice).toLocaleString()
        comparisonData[1].binance.change = parseFloat(ethResponse.data.priceChangePercent)
        
        comparisonData[2].binance.price = parseFloat(bnbResponse.data.lastPrice).toLocaleString()
        comparisonData[2].binance.change = parseFloat(bnbResponse.data.priceChangePercent)
        
        comparisonData[3].binance.price = parseFloat(solResponse.data.lastPrice).toLocaleString()
        comparisonData[3].binance.change = parseFloat(solResponse.data.priceChangePercent)
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 获取K线数据
        const klineResponse = await axios.get('https://api.binance.com/api/v3/klines', {
          params: {
            symbol: 'BTCUSDT',
            interval: '1d',
            limit: 100
          }
        })
        
        // 更新K线图表，仅当当前选中的数据源是Binance时
        if (selectedDataSource.value === 'binance') {
          updateChartWithBinanceData(klineResponse.data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'Binance数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取Binance数据失败:', error)
        ElMessage({
          message: '获取Binance数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 获取CryptoCompare数据
    const fetchCryptoCompareData = async (showMessage = true) => {
      try {
        isLoading.value = true
        
        // 获取多个币种的价格数据
        const priceResponse = await axios.get('https://min-api.cryptocompare.com/data/pricemultifull', {
          params: {
            fsyms: 'BTC,ETH,BNB,SOL',
            tsyms: 'USD'
          }
        })
        
        const data = priceResponse.data.RAW
        
        // 更新市场概览数据
        marketOverview[0].price = data.BTC.USD.PRICE.toLocaleString()
        marketOverview[0].change = parseFloat(data.BTC.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[1].price = data.ETH.USD.PRICE.toLocaleString()
        marketOverview[1].change = parseFloat(data.ETH.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[2].price = data.BNB.USD.PRICE.toLocaleString()
        marketOverview[2].change = parseFloat(data.BNB.USD.CHANGEPCT24HOUR.toFixed(2))
        
        marketOverview[3].price = data.SOL.USD.PRICE.toLocaleString()
        marketOverview[3].change = parseFloat(data.SOL.USD.CHANGEPCT24HOUR.toFixed(2))
        
        // 更新比较数据
        comparisonData[0].cryptocompare.price = data.BTC.USD.PRICE.toLocaleString()
        comparisonData[0].cryptocompare.change = parseFloat(data.BTC.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[1].cryptocompare.price = data.ETH.USD.PRICE.toLocaleString()
        comparisonData[1].cryptocompare.change = parseFloat(data.ETH.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[2].cryptocompare.price = data.BNB.USD.PRICE.toLocaleString()
        comparisonData[2].cryptocompare.change = parseFloat(data.BNB.USD.CHANGEPCT24HOUR.toFixed(2))
        
        comparisonData[3].cryptocompare.price = data.SOL.USD.PRICE.toLocaleString()
        comparisonData[3].cryptocompare.change = parseFloat(data.SOL.USD.CHANGEPCT24HOUR.toFixed(2))
        
        // 计算价格差异
        comparisonData.forEach(item => calculatePriceDiff(item.symbol))
        
        // 获取历史K线数据
        const historyResponse = await axios.get('https://min-api.cryptocompare.com/data/v2/histoday', {
          params: {
            fsym: 'BTC',
            tsym: 'USD',
            limit: 100
          }
        })
        
        // 更新K线图表，仅当当前选中的数据源是CryptoCompare时
        if (selectedDataSource.value === 'cryptocompare') {
          updateChartWithCryptoCompareData(historyResponse.data.Data.Data)
        }
        
        if (showMessage) {
          lastUpdated.value = new Date().toLocaleString()
          ElMessage({
            message: 'CryptoCompare数据更新成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('获取CryptoCompare数据失败:', error)
        ElMessage({
          message: '获取CryptoCompare数据失败，请稍后重试',
          type: 'error'
        })
      } finally {
        isLoading.value = false
      }
    }
    
    // 根据选择的数据源获取数据
    const fetchDataBySource = () => {
      switch (selectedDataSource.value) {
        case 'coingecko':
          fetchCoinGeckoData()
          break
        case 'binance':
          fetchBinanceData()
          break
        case 'cryptocompare':
          fetchCryptoCompareData()
          break
      }
    }

    // 交易对选择
    const symbols = [
      { value: 'BTC/USDT', label: 'BTC/USDT' },
      { value: 'ETH/USDT', label: 'ETH/USDT' },
      { value: 'BNB/USDT', label: 'BNB/USDT' },
      { value: 'SOL/USDT', label: 'SOL/USDT' }
    ]
    const selectedSymbol = ref('BTC/USDT')
    
    // Binance 图表相关
    const binanceSymbol = ref('BTCUSDT')
    const binanceWebview = ref(null)
    const binanceCurrentPrice = ref(0) // 新增：当前Binance图表对应的实时价格
    const binancePriceUpdateInterval = ref(null) // 新增：价格更新定时器
    
    // OKX 图表相关
    const okxSymbol = ref('btc-usdt')
    const okxWebview = ref(null)
    const okxCurrentPrice = ref(0) // 新增：当前OKX图表对应的实时价格
    const okxPriceUpdateInterval = ref(null) // 新增：价格更新定时器
    
    // 更新 Binance 图表
    const updateBinanceChart = (newSymbol) => {
      binanceSymbol.value = newSymbol
      if (binanceWebview.value) {
        binanceWebview.value.src = `https://www.binance.com/zh-CN/trade/${newSymbol}?theme=dark&type=spot`
      }
      
      // 启动对应交易对的实时价格监控
      startBinancePriceMonitoring(newSymbol)
      
      // 同时更新OKX图表的交易对（格式转换：BTCUSDT -> btc-usdt）
      const okxSymbolFormat = newSymbol.replace('USDT', '-USDT').toLowerCase()
      okxSymbol.value = okxSymbolFormat
      if (okxWebview.value) {
        okxWebview.value.src = `https://www.okx.com/en-us/trade-spot/${okxSymbolFormat}`
      }
      
      // 启动OKX对应交易对的实时价格监控
      startOKXPriceMonitoring(okxSymbolFormat)
    }
    
    // 更新 OKX 图表
    const updateOKXChart = (newSymbol) => {
      okxSymbol.value = newSymbol
      if (okxWebview.value) {
        okxWebview.value.src = `https://www.okx.com/en-us/trade-spot/${newSymbol}`
      }
      
      // 启动对应交易对的实时价格监控
      startOKXPriceMonitoring(newSymbol)
      
      // 同时更新Binance图表的交易对（格式转换：btc-usdt -> BTCUSDT）
      const binanceSymbolFormat = newSymbol.replace('-USDT', 'USDT').toUpperCase()
      binanceSymbol.value = binanceSymbolFormat
      if (binanceWebview.value) {
        binanceWebview.value.src = `https://www.binance.com/zh-CN/trade/${binanceSymbolFormat}?theme=dark&type=spot`
      }
      
      // 启动Binance对应交易对的实时价格监控
      startBinancePriceMonitoring(binanceSymbolFormat)
    }
    
    // 启动Binance价格实时监控
    const startBinancePriceMonitoring = (symbol) => {
      // 清除现有定时器
      if (binancePriceUpdateInterval.value) {
        clearInterval(binancePriceUpdateInterval.value)
      }
      
      // 立即获取一次价格
      fetchBinanceRealTimePrice(symbol)
      
      // 每5秒获取一次实时价格，与Binance图表刷新频率保持同步
      binancePriceUpdateInterval.value = setInterval(() => {
        fetchBinanceRealTimePrice(symbol)
      }, 5000) // 5秒间隔，确保与图表更新同步
      
      console.log(`🔄 开始监控 ${symbol} 的实时价格`)
    }
    
    // 启动OKX价格实时监控
    const startOKXPriceMonitoring = (symbol) => {
      // 清除现有定时器
      if (okxPriceUpdateInterval.value) {
        clearInterval(okxPriceUpdateInterval.value)
      }
      
      // 立即获取一次价格
      fetchOKXRealTimePrice(symbol)
      
      // 每5秒获取一次实时价格，与OKX图表刷新频率保持同步
      okxPriceUpdateInterval.value = setInterval(() => {
        fetchOKXRealTimePrice(symbol)
      }, 5000) // 5秒间隔，确保与图表更新同步
      
      console.log(`🔄 开始监控 OKX ${symbol} 的实时价格`)
    }
    
    // 获取Binance实时价格
    const fetchBinanceRealTimePrice = async (symbol) => {
      try {
        const response = await axios.get('https://api.binance.com/api/v3/ticker/price', {
          params: { symbol },
          timeout: 3000
        })
        
        if (response.data && response.data.price) {
          const newPrice = parseFloat(response.data.price)
          const oldPrice = binanceCurrentPrice.value
          binanceCurrentPrice.value = newPrice
          
          // 同步更新市场概览中对应的价格
          updateMarketOverviewPrice(symbol, newPrice)
          
          // 如果虚拟交易正在运行且交易对匹配，同步更新虚拟交易价格
          updateVirtualTradingPrice(symbol, newPrice)
          
          // 价格变化提示（仅在价格有显著变化时显示）
          if (oldPrice > 0 && Math.abs((newPrice - oldPrice) / oldPrice) > 0.001) { // 0.1%以上变化
            console.log(`💰 ${symbol} 价格更新: $${oldPrice.toFixed(2)} → $${newPrice.toFixed(2)}`)
          }
        }
      } catch (error) {
        console.warn(`获取 ${symbol} 实时价格失败:`, error.message)
      }
    }
    
    // 获取OKX实时价格
    const fetchOKXRealTimePrice = async (symbol) => {
      try {
        // 将符号格式从 btc-usdt 转换为 BTC-USDT
        const formattedSymbol = symbol.toUpperCase()
        const response = await axios.get('https://www.okx.com/api/v5/market/ticker', {
          params: { instId: formattedSymbol },
          timeout: 3000
        })
        
        if (response.data && response.data.data && response.data.data[0] && response.data.data[0].last) {
          const newPrice = parseFloat(response.data.data[0].last)
          const oldPrice = okxCurrentPrice.value
          okxCurrentPrice.value = newPrice
          
          // 价格变化提示（仅在价格有显著变化时显示）
          if (oldPrice > 0 && Math.abs((newPrice - oldPrice) / oldPrice) > 0.001) { // 0.1%以上变化
            console.log(`💰 OKX ${symbol} 价格更新: $${oldPrice.toFixed(2)} → $${newPrice.toFixed(2)}`)
          }
        }
      } catch (error) {
        console.warn(`获取 OKX ${symbol} 实时价格失败:`, error.message)
      }
    }
    
    // 同步更新市场概览价格
    const updateMarketOverviewPrice = (binanceSymbol, price) => {
      const symbolMap = {
        'BTCUSDT': 0,
        'ETHUSDT': 1,
        'BNBUSDT': 2,
        'SOLUSDT': 3
      }
      
      const index = symbolMap[binanceSymbol]
      if (index !== undefined && marketOverview[index]) {
        const oldPrice = parseFloat(marketOverview[index].price.replace(/,/g, '')) || 0
        marketOverview[index].price = price.toLocaleString()
        
        // 计算实时涨跌幅（基于之前的价格）
        if (oldPrice > 0) {
          const changePercent = ((price - oldPrice) / oldPrice) * 100
          if (Math.abs(changePercent) > 0.01) { // 0.01%以上变化才更新
            marketOverview[index].change = parseFloat(changePercent.toFixed(2))
          }
        }
        
        console.log(`📊 市场概览更新: ${marketOverview[index].name} = $${price.toLocaleString()}`)
      }
    }
    
    // 同步更新虚拟交易价格
    const updateVirtualTradingPrice = (binanceSymbol, price) => {
      if (!isVirtualTrading.value) return
      
      // 检查当前虚拟交易的交易对是否与Binance图表匹配
      const currentVirtualSymbol = backtestSettings.symbol.replace('/', '')
      if (currentVirtualSymbol === binanceSymbol) {
        // 更新虚拟交易的当前价格
        virtualTradingResults.currentPrice = price
        virtualTradingResults.lastUpdateTime = Date.now()
        
        // 添加到价格历史
        const now = Date.now()
        const priceData = {
          date: new Date(now).toISOString().split('T')[0],
          time: new Date(now).toLocaleTimeString(),
          close: price,
          timestamp: now
        }
        
        virtualTradingResults.priceHistory.push(priceData)
        
        // 保持最近100个价格数据点
        if (virtualTradingResults.priceHistory.length > 100) {
          virtualTradingResults.priceHistory = virtualTradingResults.priceHistory.slice(-100)
        }
        
        // 更新虚拟账户价值
        updateVirtualAccount()
        
        console.log(`🎯 虚拟交易价格同步: ${backtestSettings.symbol} = $${price.toFixed(2)}`)
      }
    }
    
    // 停止Binance价格监控
    const stopBinancePriceMonitoring = () => {
      if (binancePriceUpdateInterval.value) {
        clearInterval(binancePriceUpdateInterval.value)
        binancePriceUpdateInterval.value = null
        console.log('⏹️ 停止Binance价格监控')
      }
    }
    
    // 停止OKX价格监控
    const stopOKXPriceMonitoring = () => {
      if (okxPriceUpdateInterval.value) {
        clearInterval(okxPriceUpdateInterval.value)
        okxPriceUpdateInterval.value = null
        console.log('⏹️ 停止OKX价格监控')
      }
    }

    // 图表实例
    let chartInstance = null
    const tradingChart = ref(null)

    // 更新图表数据 - CoinGecko
    const updateChartData = (data) => {
      if (!chartInstance) return
      
      // 由于CoinGecko API不直接提供K线数据，我们使用模拟数据
      // 但使用实际价格作为基准
      const basePrice = data.bitcoin.usd
      const klineData = generateKLineData(basePrice)
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: CoinGecko`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: klineData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: klineData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 更新图表数据 - Binance
    const updateChartWithBinanceData = (klineData) => {
      if (!chartInstance) return
      
      // Binance K线数据格式转换
      // [开盘时间, 开盘价, 最高价, 最低价, 收盘价, 成交量, 收盘时间, ...]
      const formattedData = klineData.map(item => {
        const date = new Date(item[0])
        return [
          date.toISOString().split('T')[0],
          parseFloat(item[1]), // 开盘价
          parseFloat(item[4]), // 收盘价
          parseFloat(item[3]), // 最低价
          parseFloat(item[2])  // 最高价
        ]
      })
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: Binance`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: formattedData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: formattedData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 更新图表数据 - CryptoCompare
    const updateChartWithCryptoCompareData = (historyData) => {
      if (!chartInstance) return
      
      // CryptoCompare数据格式转换
      const formattedData = historyData.map(item => {
        const date = new Date(item.time * 1000)
        return [
          date.toISOString().split('T')[0],
          item.open,
          item.close,
          item.low,
          item.high
        ]
      })
      
      const option = {
        title: {
          text: `BTC/USDT - 数据来源: CryptoCompare`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: formattedData.map(item => item[0]),
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          splitNumber: 20
        },
        yAxis: {
          scale: true,
          splitLine: { show: true }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            bottom: '5%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: 'BTC/USDT',
            type: 'candlestick',
            data: formattedData.map(item => item.slice(1)),
            itemStyle: {
              color: '#ef232a',
              color0: '#14b143',
              borderColor: '#ef232a',
              borderColor0: '#14b143'
            }
          }
        ]
      }
      
      chartInstance.setOption(option, true)
    }
    
    // 初始化图表
    const initChart = () => {
      if (tradingChart.value) {
        chartInstance = echarts.init(tradingChart.value)
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
          chartInstance.resize()
        })
        
        // 加载初始数据
        fetchDataBySource()
      }
    }
    
    // 生成模拟K线数据
    const generateKLineData = () => {
      const basePrice = 45000
      const data = []
      const today = new Date()
      
      for (let i = 0; i < 100; i++) {
        const date = new Date(today)
        date.setDate(date.getDate() - (100 - i))
        const dateStr = date.toISOString().split('T')[0]
        
        const open = basePrice + Math.random() * 2000 - 1000
        const close = open + Math.random() * 1000 - 500
        const low = Math.min(open, close) - Math.random() * 500
        const high = Math.max(open, close) + Math.random() * 500
        
        data.push([dateStr, open, close, low, high])
      }
      
      return data
    }
    
    onMounted(() => {
      // 初始化网络监控
      setupNetworkMonitoring()
      
      // 设置页面状态处理器
      const cleanupPageHandlers = setupPageStateHandlers()
      
      // 将清理函数保存到组件实例上，以便在unmounted时调用
      window._pageHandlersCleanup = cleanupPageHandlers
      
      // 首次加载时获取所有数据源的数据
      fetchAllDataSources()
      
      // 启动Binance图表对应交易对的实时价格监控
      startBinancePriceMonitoring(binanceSymbol.value)
      
      // 启动OKX图表对应交易对的实时价格监控
      startOKXPriceMonitoring(okxSymbol.value)
      
      // 启动搬砖套利监控
      updateArbitrageData()
      
      // 检查是否有保存的虚拟交易状态
      setTimeout(() => {
        const savedState = loadVirtualTradingState()
        if (savedState && savedState.isActive) {
          ElMessageBox.confirm(
            `检测到上次未完成的虚拟交易：\n` +
            `交易对: ${savedState.symbol}\n` +
            `策略: ${savedState.strategy}\n` +
            `当前盈亏: ${savedState.pnlPercent.toFixed(2)}%\n` +
            `交易次数: ${savedState.trades.length}\n` +
            `最后更新: ${new Date(savedState.lastUpdated).toLocaleString()}\n\n` +
            `是否自动恢复上次的虚拟交易状态？`,
            '恢复虚拟交易',
            {
              confirmButtonText: '自动恢复',
              cancelButtonText: '稍后手动',
              type: 'question',
              center: true
            }
          ).then(() => {
            // 用户选择自动恢复
            restoreVirtualTradingState(savedState)
          }).catch(() => {
            // 用户选择稍后手动，不做任何操作
            console.log('用户选择稍后手动恢复虚拟交易')
          })
        }
      }, 2000) // 延迟2秒显示，等待页面加载完成
      
      // 启动自动刷新
      startAutoRefresh()
    })
    
    onUnmounted(() => {
      // 停止自动刷新
      stopAutoRefresh()
      
      // 停止Binance价格监控
      stopBinancePriceMonitoring()
      
      // 停止OKX价格监控
      stopOKXPriceMonitoring()
      
      // 清理虚拟交易定时器
      if (virtualTradingInterval.value) {
        clearInterval(virtualTradingInterval.value)
      }
      
      // 清理搬砖套利监控定时器
      if (window._arbitrageInterval) {
        clearInterval(window._arbitrageInterval)
        window._arbitrageInterval = null
      }
      
      // 在组件销毁前保存状态
      if (isVirtualTrading.value) {
        console.log('💾 组件销毁，保存虚拟交易状态')
        saveVirtualTradingState()
      }
      
      // 清理页面状态处理器
      if (window._pageHandlersCleanup) {
        window._pageHandlersCleanup()
        window._pageHandlersCleanup = null
      }
    })
    
    // 回测相关变量
    const backtestSettings = reactive({
      symbol: 'BTC/USDT',
      period: '30d',
      interval: '1d',
      strategyType: 'ma_cross',
      dataSource: 'real', // 新增：数据源选择
      initialCapital: 10000,
      tradeAmount: 20,
      fastMAPeriod: 9,
      slowMAPeriod: 21,
      rsiPeriod: 14,
      overbought: 70,
      oversold: 30,
      bbPeriod: 20,
      bbStdDev: 2,
      customStrategy: '',
      stopLoss: 5,
      takeProfit: 10,
      maxPosition: 80, // 新增：最大仓位比例
      riskControl: true, // 新增：风险控制开关
      dynamicPositioning: false, // 新增：动态仓位管理
      maxDrawdownLimit: 15, // 新增：最大回撤限制
      // AI智能策略1参数
      mlConfidenceThreshold: 0.75, // 模型置信度阈值
      mlFeatureWeighting: 'balanced', // 特征权重模式
      mlMarketStateAware: true, // 市场状态感知
      mlDynamicPositioning: true, // 动态仓位管理
      mlSentimentWeight: 0.5, // 情绪指标权重
      mlAdaptiveStopLoss: 1.5, // 智能止损系数
      // 新增高级AI参数
      mlRiskFilter: true, // 风险过滤器
      mlSignalThreshold: 0.55, // 信号强度阈值
      mlMultiFactorMode: 'adaptive' // 多因子融合模式
    })
    
    const isBacktesting = ref(false)
    const backtestResults = ref({ equityCurve: [], trades: [] })
    const backtestTrades = ref([])
    const backtestSummary = reactive({
      totalReturn: 0,
      annualReturn: 0,
      sharpeRatio: 0,
      maxDrawdown: 0,
      winRate: 0,
      totalTrades: 0
    })
    const backtestChart = ref(null)
    const backtestChartInstance = ref(null)
    
    // 虚拟交易相关变量
    const isVirtualTrading = ref(false)
    const virtualTradingInterval = ref(null)
    const virtualTradingData = ref([])
    const virtualCurrentIndex = ref(0)
    const virtualTradingResults = reactive({
      cash: 0,
      position: 0,
      totalValue: 0,
      trades: [],
      currentPrice: 0,
      pnl: 0,
      pnlPercent: 0,
      priceHistory: [], // 新增：用于存储价格历史计算技术指标
      lastSignalTime: 0, // 新增：防止频繁交易
      lastUpdateTime: 0, // 新增：记录最后更新时间
      priceCache: null, // 新增：价格缓存
      cacheExpiry: 0, // 新增：缓存过期时间
      // 风险控制相关
      maxDrawdownReached: 0, // 最大回撤记录
      currentDrawdown: 0, // 当前回撤
      riskLocked: false, // 风险锁定状态
      lastStopLoss: null, // 最后一次止损价格
      lastTakeProfit: null, // 最后一次止盈价格
      positionValue: 0, // 当前仓位价值
      riskEvents: [], // 风险事件记录
      // 新增：当前会话交易跟踪
      currentSessionTradesCount: 0, // 当前会话的交易次数
      sessionStartTime: null // 会话开始时间
    })
    
    // 监听页面刷新和关闭事件，确保状态保存
    const setupPageStateHandlers = () => {
      // 监听页面刷新/关闭事件
      const handleBeforeUnload = (event) => {
        if (isVirtualTrading.value) {
          console.log('💾 页面即将关闭/刷新，保存虚拟交易状态')
          saveVirtualTradingState()
          
          // 在页面关闭时显示确认对话框
          const message = '虚拟交易正在运行中，确定要离开吗？状态已保存。'
          event.preventDefault()
          event.returnValue = message
          return message
        }
      }
      
      // 监听页面隐藏事件（切换标签页等）
      const handleVisibilityChange = () => {
        if (document.hidden && isVirtualTrading.value) {
          console.log('💾 页面隐藏，保存虚拟交易状态')
          saveVirtualTradingState()
        }
      }
      
      // 监听浏览器焦点丢失事件
      const handleBlur = () => {
        if (isVirtualTrading.value) {
          console.log('💾 浏览器失去焦点，保存虚拟交易状态')
          saveVirtualTradingState()
        }
      }
      
      // 添加事件监听器
      window.addEventListener('beforeunload', handleBeforeUnload)
      document.addEventListener('visibilitychange', handleVisibilityChange)
      window.addEventListener('blur', handleBlur)
      
      // 返回清理函数
      return () => {
        window.removeEventListener('beforeunload', handleBeforeUnload)
        document.removeEventListener('visibilitychange', handleVisibilityChange)
        window.removeEventListener('blur', handleBlur)
      }
    }
    const networkStatus = ref({
      online: navigator.onLine,
      lastSuccessTime: Date.now(),
      retryCount: 0,
      maxRetries: 5
    })
    
    // 监控网络状态变化
    const setupNetworkMonitoring = () => {
      window.addEventListener('online', () => {
        networkStatus.value.online = true
        networkStatus.value.retryCount = 0
        console.log('🟢 网络连接恢复')
        ElMessage({
          message: '网络连接恢复，虚拟交易继续运行',
          type: 'success'
        })
      })
      
      window.addEventListener('offline', () => {
        networkStatus.value.online = false
        console.log('🔴 网络连接中断')
        ElMessage({
          message: '网络连接中断，虚拟交易暂停',
          type: 'warning'
        })
      })
    }
    
    // 智能重试机制
    const smartRetry = async (operation, context = '') => {
      const maxRetries = networkStatus.value.maxRetries
      
      for (let i = 0; i < maxRetries; i++) {
        try {
          const result = await operation()
          networkStatus.value.lastSuccessTime = Date.now()
          networkStatus.value.retryCount = 0
          return result
        } catch (error) {
          networkStatus.value.retryCount = i + 1
          console.warn(`${context} 尝试 ${i + 1}/${maxRetries} 失败:`, error.message)
          
          if (i === maxRetries - 1) {
            console.error(`${context} 所有重试尝试均失败`)
            throw error
          }
          
          // 指数退避：1s, 2s, 4s, 8s
          const delay = Math.pow(2, i) * 1000
          console.log(`等待 ${delay}ms 后重试...`)
          await new Promise(resolve => setTimeout(resolve, delay))
        }
      }
    }
    const VIRTUAL_TRADING_STATE_KEY = 'crypto_bot_virtual_trading_state'
    
    // 优化后的状态保存（添加错误处理和数据验证）
    const saveVirtualTradingState = () => {
      try {
        // 数据验证
        if (!isVirtualTrading.value && virtualTradingResults.trades.length === 0) {
          console.log('没有需要保存的数据')
          return
        }
        
        const stateData = {
          isActive: isVirtualTrading.value,
          symbol: backtestSettings.symbol,
          strategy: backtestSettings.strategyType,
          startTime: new Date().toISOString(),
          cash: virtualTradingResults.cash,
          position: virtualTradingResults.position,
          totalValue: virtualTradingResults.totalValue,
          currentPrice: virtualTradingResults.currentPrice,
          pnl: virtualTradingResults.pnl,
          pnlPercent: virtualTradingResults.pnlPercent,
          trades: virtualTradingResults.trades,
          priceHistory: virtualTradingResults.priceHistory.slice(-50), // 只保存最近50个价格点
          lastSignalTime: virtualTradingResults.lastSignalTime,
          // 风险控制状态
          maxDrawdownReached: virtualTradingResults.maxDrawdownReached,
          currentDrawdown: virtualTradingResults.currentDrawdown,
          riskLocked: virtualTradingResults.riskLocked,
          lastStopLoss: virtualTradingResults.lastStopLoss,
          lastTakeProfit: virtualTradingResults.lastTakeProfit,
          positionValue: virtualTradingResults.positionValue,
          riskEvents: virtualTradingResults.riskEvents.slice(-10), // 只保存最近10个风险事件
          // 当前会话交易跟踪
          currentSessionTradesCount: virtualTradingResults.currentSessionTradesCount,
          sessionStartTime: virtualTradingResults.sessionStartTime,
          settings: {
            symbol: backtestSettings.symbol, // 添加交易对保存
            initialCapital: backtestSettings.initialCapital,
            tradeAmount: backtestSettings.tradeAmount,
            fastMAPeriod: backtestSettings.fastMAPeriod,
            slowMAPeriod: backtestSettings.slowMAPeriod,
            rsiPeriod: backtestSettings.rsiPeriod,
            overbought: backtestSettings.overbought,
            oversold: backtestSettings.oversold,
            bbPeriod: backtestSettings.bbPeriod,
            bbStdDev: backtestSettings.bbStdDev,
            stopLoss: backtestSettings.stopLoss,
            takeProfit: backtestSettings.takeProfit,
            maxPosition: backtestSettings.maxPosition,
            riskControl: backtestSettings.riskControl,
            maxDrawdownLimit: backtestSettings.maxDrawdownLimit,
            strategyType: backtestSettings.strategyType, // 添加策略类型保存
            period: backtestSettings.period, // 添加周期保存
            interval: backtestSettings.interval, // 添加K线周期保存
            dataSource: backtestSettings.dataSource, // 添加数据源保存
            // AI智能策略1参数
            mlConfidenceThreshold: backtestSettings.mlConfidenceThreshold,
            mlFeatureWeighting: backtestSettings.mlFeatureWeighting,
            mlMarketStateAware: backtestSettings.mlMarketStateAware,
            mlDynamicPositioning: backtestSettings.mlDynamicPositioning,
            mlSentimentWeight: backtestSettings.mlSentimentWeight,
            mlAdaptiveStopLoss: backtestSettings.mlAdaptiveStopLoss,
            // 新增高级AI参数
            mlRiskFilter: backtestSettings.mlRiskFilter,
            mlSignalThreshold: backtestSettings.mlSignalThreshold,
            mlMultiFactorMode: backtestSettings.mlMultiFactorMode
          },
          lastUpdated: new Date().toISOString(),
          version: '2.0' // 版本标识
        }
        
        // 检查数据大小（限制在5MB以内）
        const dataSize = JSON.stringify(stateData).length
        const maxSize = 5 * 1024 * 1024 // 5MB
        
        if (dataSize > maxSize) {
          console.warn(`状态数据过大（${(dataSize / 1024 / 1024).toFixed(2)}MB），精简数据`)
          // 精简数据
          stateData.trades = stateData.trades.slice(-100) // 只保存最近100笔交易
          stateData.priceHistory = stateData.priceHistory.slice(-30) // 只保存最近30个价格点
          stateData.riskEvents = stateData.riskEvents.slice(-5) // 只保存最近5个风险事件
        }
        
        localStorage.setItem(VIRTUAL_TRADING_STATE_KEY, JSON.stringify(stateData))
        console.log(`✅ 虚拟交易状态已保存（${(dataSize / 1024).toFixed(1)}KB）`)
      } catch (error) {
        console.error('❌ 保存虚拟交易状态失败:', error)
        
        // 尝试清理旧数据后重试
        try {
          localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
          console.log('已清理旧状态数据')
        } catch (cleanupError) {
          console.error('清理旧状态数据失败:', cleanupError)
        }
        
        ElMessage({
          message: '保存虚拟交易状态失败，请检查浏览器存储空间',
          type: 'warning'
        })
      }
    }
    
    // 优化后的状态加载（添加版本兼容性和数据验证）
    const loadVirtualTradingState = () => {
      try {
        const stateJson = localStorage.getItem(VIRTUAL_TRADING_STATE_KEY)
        if (!stateJson) {
          console.log('⚠️ 未找到保存的虚拟交易状态')
          return null
        }
        
        const stateData = JSON.parse(stateJson)
        
        // 版本兼容性检查
        const version = stateData.version || '1.0'
        if (version !== '2.0') {
          console.log('旧版本数据，将进行升级')
          return migrateOldStateData(stateData)
        }
        
        // 验证状态数据完整性
        const requiredFields = ['isActive', 'symbol', 'strategy', 'cash', 'position', 'totalValue']
        const missingFields = requiredFields.filter(field => !(field in stateData))
        
        if (missingFields.length > 0) {
          console.error('❌ 状态数据不完整，缺少字段:', missingFields)
          return null
        }
        
        // 数据合理性检查
        if (stateData.cash < 0 || stateData.position < 0 || stateData.totalValue < 0) {
          console.error('❌ 状态数据包含负值，可能已损坏')
          return null
        }
        
        // 检查数据时效性（24小时内的数据才有效）
        const lastUpdated = new Date(stateData.lastUpdated)
        const now = new Date()
        const hoursDiff = (now - lastUpdated) / (1000 * 60 * 60)
        
        if (hoursDiff > 24) {
          console.log(`⚠️ 状态数据过旧（${hoursDiff.toFixed(1)}小时前），建议清理`)
          // 不返回null，但给出警告
        }
        
        console.log('✅ 虚拟交易状态加载成功')
        console.log(`📅 最后更新: ${stateData.lastUpdated}`)
        console.log(`💰 当前盈亏: ${stateData.pnlPercent?.toFixed(2) || 0}%`)
        return stateData
      } catch (error) {
        console.error('❌ 加载虚拟交易状态失败:', error)
        
        // 尝试清理损坏的数据
        try {
          localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
          console.log('已清理损坏的状态数据')
        } catch (cleanupError) {
          console.error('清理损坏数据失败:', cleanupError)
        }
        
        return null
      }
    }
    
    // 迁移旧版本数据
    const migrateOldStateData = (oldData) => {
      try {
        console.log('开始迁移旧版本数据...')
        
        const migratedData = {
          ...oldData,
          version: '2.0',
          // 添加新字段的默认值
          maxDrawdownReached: oldData.maxDrawdownReached || 0,
          currentDrawdown: oldData.currentDrawdown || 0,
          riskLocked: oldData.riskLocked || false,
          lastStopLoss: oldData.lastStopLoss || null,
          lastTakeProfit: oldData.lastTakeProfit || null,
          positionValue: oldData.positionValue || 0,
          riskEvents: oldData.riskEvents || [],
          settings: {
            ...oldData.settings,
            symbol: oldData.symbol || oldData.settings?.symbol || 'BTC/USDT', // 恢复交易对
            strategyType: oldData.strategy || oldData.settings?.strategyType || 'ma_cross', // 恢复策略类型
            period: oldData.settings?.period || '30d',
            interval: oldData.settings?.interval || '1d',
            dataSource: oldData.settings?.dataSource || 'real',
            maxPosition: oldData.settings?.maxPosition || 80,
            riskControl: oldData.settings?.riskControl !== undefined ? oldData.settings.riskControl : true,
            maxDrawdownLimit: oldData.settings?.maxDrawdownLimit || 15
          }
        }
        
        // 保存迁移后的数据
        localStorage.setItem(VIRTUAL_TRADING_STATE_KEY, JSON.stringify(migratedData))
        console.log('✅ 数据迁移完成')
        
        return migratedData
      } catch (error) {
        console.error('❌ 数据迁移失败:', error)
        return null
      }
    }
    
    // 恢复虚拟交易状态
    const restoreVirtualTradingState = (stateData) => {
      try {
        // 恢复交易设置（包括交易对信息）
        if (stateData.settings) {
          Object.assign(backtestSettings, stateData.settings)
        }
        
        // 兼容性处理：从外层symbol字段恢复交易对（针对旧版本数据）
        if (stateData.symbol && !stateData.settings?.symbol) {
          backtestSettings.symbol = stateData.symbol
        }
        
        // 兼容性处理：从外层strategy字段恢复策略类型（针对旧版本数据）
        if (stateData.strategy && !stateData.settings?.strategyType) {
          backtestSettings.strategyType = stateData.strategy
        }
        
        console.log(`🔄 恢复交易对: ${backtestSettings.symbol}, 策略: ${backtestSettings.strategyType}`)
        
        // 恢复虚拟交易数据
        Object.assign(virtualTradingResults, {
          cash: stateData.cash || 0,
          position: stateData.position || 0,
          totalValue: stateData.totalValue || 0,
          currentPrice: stateData.currentPrice || 0,
          pnl: stateData.pnl || 0,
          pnlPercent: stateData.pnlPercent || 0,
          trades: stateData.trades || [],
          priceHistory: stateData.priceHistory || [],
          lastSignalTime: stateData.lastSignalTime || 0,
          // 恢复当前会话交易计数器（重新开始计数）
          currentSessionTradesCount: 0, // 重新开始计数当前会话
          sessionStartTime: new Date().toISOString() // 记录新会话开始时间
        })
        
        // 恢复虚拟交易状态
        if (stateData.isActive) {
          isVirtualTrading.value = true
          
          // 自动切换Binance图表到对应的交易对页面
          const binanceSymbolFormat = backtestSettings.symbol.replace('/', '')
          updateBinanceChart(binanceSymbolFormat)
          
          // 重新启动虚拟交易定时器
          virtualTradingInterval.value = setInterval(() => {
            updateVirtualTradingWithRealData()
          }, 5000)
          
          ElMessage({
            message: `虚拟交易状态已恢复，当前盈亏: ${stateData.pnlPercent.toFixed(2)}%`,
            type: 'success',
            duration: 4000
          })
          
          console.log('🔄 虚拟交易已恢复运行')
        }
        
        return true
      } catch (error) {
        console.error('❌ 恢复虚拟交易状态失败:', error)
        ElMessage({
          message: '恢复虚拟交易状态失败',
          type: 'error'
        })
        return false
      }
    }
    
    // 手动保存状态（用于调试和用户主动保存）
    const manualSaveState = () => {
      try {
        saveVirtualTradingState()
        ElMessage({
          message: '状态已手动保存成功',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        ElMessage({
          message: '手动保存状态失败: ' + error.message,
          type: 'error'
        })
      }
    }
    const clearVirtualTradingState = () => {
      try {
        localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
        console.log('🗑️ 虚拟交易状态已清理')
        ElMessage({
          message: '虚拟交易状态已清理',
          type: 'success'
        })
      } catch (error) {
        console.error('❌ 清理虚拟交易状态失败:', error)
      }
    }
    
    // 导出虚拟交易数据
    const exportVirtualTradingData = () => {
      try {
        if (!virtualTradingResults.trades || virtualTradingResults.trades.length === 0) {
          ElMessage({
            message: '没有交易数据可导出',
            type: 'warning'
          })
          return
        }
        
        // 准备导出数据
        const exportData = {
          summary: {
            symbol: backtestSettings.symbol,
            strategy: backtestSettings.strategyType,
            initialCapital: backtestSettings.initialCapital,
            finalValue: virtualTradingResults.totalValue,
            totalPnL: virtualTradingResults.pnl,
            totalPnLPercent: virtualTradingResults.pnlPercent,
            totalTrades: virtualTradingResults.trades.length,
            exportTime: new Date().toISOString(),
            timePeriod: {
              start: virtualTradingResults.trades[0]?.date || 'N/A',
              end: virtualTradingResults.trades[virtualTradingResults.trades.length - 1]?.date || 'N/A'
            }
          },
          trades: virtualTradingResults.trades.map(trade => ({
            id: trade.id,
            date: trade.date,
            time: trade.time,
            type: trade.type,
            price: trade.price,
            amount: trade.amount,
            value: trade.value,
            profit: trade.profit || 0,
            reason: trade.reason,
            isRealTime: trade.isRealTime || false
          })),
          statistics: calculateVirtualTradingStatistics()
        }
        
        // 生成文件名
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-').substring(0, 19)
        const filename = `virtual_trading_${backtestSettings.symbol.replace('/', '')}_${timestamp}`
        
        // 导出JSON格式
        const jsonContent = JSON.stringify(exportData, null, 2)
        downloadFile(jsonContent, `${filename}.json`, 'application/json')
        
        // 导出CSV格式
        const csvContent = generateCSV(exportData.trades)
        downloadFile(csvContent, `${filename}_trades.csv`, 'text/csv')
        
        ElMessage({
          message: `交易数据已导出（JSON + CSV）`,
          type: 'success',
          duration: 3000
        })
        
      } catch (error) {
        console.error('导出虚拟交易数据失败:', error)
        ElMessage({
          message: '导出数据失败: ' + error.message,
          type: 'error'
        })
      }
    }
    
    // 生成CSV数据
    const generateCSV = (trades) => {
      const headers = [
        '交易ID', '日期', '时间', '类型', '价格', '数量', '价值', '盈亏', '原因', '实时数据'
      ]
      
      const csvRows = [
        headers.join(',')
      ]
      
      trades.forEach(trade => {
        const row = [
          trade.id,
          trade.date,
          trade.time,
          trade.type === 'buy' ? '买入' : '卖出',
          trade.price.toFixed(2),
          trade.amount.toFixed(6),
          trade.value.toFixed(2),
          (trade.profit || 0).toFixed(2),
          `"${trade.reason}"`, // 用引号包裹以防止CSV格式问题
          trade.isRealTime ? '是' : '否'
        ]
        csvRows.push(row.join(','))
      })
      
      return csvRows.join('\n')
    }
    
    // 计算虚拟交易统计数据
    const calculateVirtualTradingStatistics = () => {
      const trades = virtualTradingResults.trades
      if (!trades || trades.length === 0) {
        return {
          totalTrades: 0,
          winningTrades: 0,
          losingTrades: 0,
          winRate: 0,
          averageWin: 0,
          averageLoss: 0,
          profitFactor: 0,
          maxWin: 0,
          maxLoss: 0,
          maxDrawdown: 0,
          maxDrawdownPercent: 0,
          sharpeRatio: 0,
          totalReturn: virtualTradingResults.pnlPercent,
          tradingDays: 0
        }
      }
      
      // 基本统计
      const totalTrades = trades.length
      const sellTrades = trades.filter(t => t.type === 'sell' && t.profit !== undefined)
      const winningTrades = sellTrades.filter(t => t.profit > 0)
      const losingTrades = sellTrades.filter(t => t.profit < 0)
      
      const winRate = sellTrades.length > 0 ? (winningTrades.length / sellTrades.length) * 100 : 0
      
      // 盈亏统计
      const totalWin = winningTrades.reduce((sum, t) => sum + t.profit, 0)
      const totalLoss = Math.abs(losingTrades.reduce((sum, t) => sum + t.profit, 0))
      const averageWin = winningTrades.length > 0 ? totalWin / winningTrades.length : 0
      const averageLoss = losingTrades.length > 0 ? totalLoss / losingTrades.length : 0
      const profitFactor = totalLoss > 0 ? totalWin / totalLoss : totalWin > 0 ? Infinity : 0
      
      const maxWin = winningTrades.length > 0 ? Math.max(...winningTrades.map(t => t.profit)) : 0
      const maxLoss = losingTrades.length > 0 ? Math.min(...losingTrades.map(t => t.profit)) : 0
      
      // 计算最大回撤
      let maxDrawdown = 0
      let maxDrawdownPercent = 0
      let peak = backtestSettings.initialCapital
      let currentCapital = backtestSettings.initialCapital
      
      trades.forEach(trade => {
        if (trade.type === 'sell' && trade.profit !== undefined) {
          currentCapital += trade.profit
          if (currentCapital > peak) {
            peak = currentCapital
          } else {
            const drawdown = peak - currentCapital
            const drawdownPercent = (drawdown / peak) * 100
            if (drawdown > maxDrawdown) {
              maxDrawdown = drawdown
              maxDrawdownPercent = drawdownPercent
            }
          }
        }
      })
      
      // 计算交易天数
      const tradeDates = [...new Set(trades.map(t => t.date))]
      const tradingDays = tradeDates.length
      
      // 简化的夏普比率计算（假设无风险收益率3%）
      const riskFreeRate = 0.03
      const annualReturn = tradingDays > 0 ? (virtualTradingResults.pnlPercent / 100) * (365 / tradingDays) : 0
      const volatility = sellTrades.length > 1 ? 
        Math.sqrt(sellTrades.reduce((sum, t) => {
          const returnRate = t.profit / backtestSettings.initialCapital
          const avgReturn = (virtualTradingResults.pnl / backtestSettings.initialCapital) / sellTrades.length
          return sum + Math.pow(returnRate - avgReturn, 2)
        }, 0) / (sellTrades.length - 1)) * Math.sqrt(365) : 0
      
      const sharpeRatio = volatility > 0 ? (annualReturn - riskFreeRate) / volatility : 0
      
      return {
        totalTrades,
        winningTrades: winningTrades.length,
        losingTrades: losingTrades.length,
        winRate: parseFloat(winRate.toFixed(2)),
        averageWin: parseFloat(averageWin.toFixed(2)),
        averageLoss: parseFloat(averageLoss.toFixed(2)),
        profitFactor: parseFloat(profitFactor.toFixed(2)),
        maxWin: parseFloat(maxWin.toFixed(2)),
        maxLoss: parseFloat(maxLoss.toFixed(2)),
        maxDrawdown: parseFloat(maxDrawdown.toFixed(2)),
        maxDrawdownPercent: parseFloat(maxDrawdownPercent.toFixed(2)),
        sharpeRatio: parseFloat(sharpeRatio.toFixed(3)),
        totalReturn: parseFloat(virtualTradingResults.pnlPercent.toFixed(2)),
        tradingDays
      }
    }
    
    // 虚拟交易统计数据（响应式）
    const virtualTradingStatistics = computed(() => {
      return calculateVirtualTradingStatistics()
    })
    
    // 运行回测
    const runBacktest = async () => {
      try {
        isBacktesting.value = true
        backtestResults.value = { equityCurve: [], trades: [] }
        backtestTrades.value = []
        
        // 模拟获取历史数据
        const historicalData = await fetchHistoricalData(backtestSettings.symbol, backtestSettings.period, backtestSettings.interval)
        
        // 根据策略类型执行回测
        switch (backtestSettings.strategyType) {
          case 'ma_cross':
            backtestResults.value = runMACrossStrategy(historicalData)
            break
          case 'rsi':
            backtestResults.value = runRSIStrategy(historicalData)
            break
          case 'bollinger':
            backtestResults.value = runBollingerStrategy(historicalData)
            break
          case 'custom':
            backtestResults.value = runCustomStrategy(historicalData)
            break
          case 'ml_strategy1':
            backtestResults.value = runMLStrategy1(historicalData)
            break
        }
        
        // 更新交易记录
        backtestTrades.value = backtestResults.value.trades || []
        
        // 计算回测结果
        calculateBacktestResults()
        
        // 等待DOM更新后绘制图表
        await nextTick()
        drawBacktestChart(backtestResults.value)
        
        ElMessage({
          message: '回测完成',
          type: 'success'
        })
      } catch (error) {
        console.error('回测失败:', error)
        ElMessage({
          message: '回测失败: ' + error.message,
          type: 'error'
        })
      } finally {
        isBacktesting.value = false
      }
    }
    
    // 启动虚拟交易
    const startVirtualTrading = async () => {
      try {
        if (isVirtualTrading.value) {
          // 停止虚拟交易
          stopVirtualTrading()
          return
        }
        
        // 检查是否有保存的状态
        const savedState = loadVirtualTradingState()
        
        if (savedState && savedState.isActive) {
          // 有保存的活跃状态，询问用户是否恢复
          const shouldRestore = await ElMessageBox.confirm(
            `检测到上次未完成的虚拟交易：\n` +
            `交易对: ${savedState.symbol}\n` +
            `策略: ${savedState.strategy}\n` +
            `当前盈亏: ${savedState.pnlPercent.toFixed(2)}%\n` +
            `交易次数: ${savedState.trades.length}\n\n` +
            `是否恢复上次的虚拟交易状态？`,
            '恢复虚拟交易',
            {
              confirmButtonText: '恢复继续',
              cancelButtonText: '重新开始',
              type: 'question'
            }
          ).catch(() => false)
          
          if (shouldRestore) {
            // 恢复之前的状态
            const restored = restoreVirtualTradingState(savedState)
            if (restored) {
              return
            }
          } else {
            // 用户选择重新开始，清理旧状态
            clearVirtualTradingState()
          }
        }
        
        // 新启动虚拟交易
        isVirtualTrading.value = true
        
        // 初始化虚拟账户
        Object.assign(virtualTradingResults, {
          cash: backtestSettings.initialCapital,
          position: 0,
          totalValue: backtestSettings.initialCapital,
          trades: [],
          currentPrice: 0,
          pnl: 0,
          pnlPercent: 0,
          priceHistory: [], // 用于存储价格历史计算技术指标
          lastSignalTime: 0, // 防止频繁交易
          lastUpdateTime: 0,
          priceCache: null,
          cacheExpiry: 0,
          // 风险控制相关
          maxDrawdownReached: 0,
          currentDrawdown: 0,
          riskLocked: false,
          lastStopLoss: null,
          lastTakeProfit: null,
          positionValue: 0,
          riskEvents: [],
          // 当前会话交易跟踪
          currentSessionTradesCount: 0,
          sessionStartTime: new Date().toISOString()
        })
        
        // 获取初始价格
        await fetchCurrentRealTimePrice()
        
        // 立即保存初始状态
        saveVirtualTradingState()
        
        // 自动切换Binance图表到对应的交易对页面
        const binanceSymbolFormat = backtestSettings.symbol.replace('/', '')
        updateBinanceChart(binanceSymbolFormat)
        
        ElMessage({
          message: `虚拟交易已启动，初始资金: $${backtestSettings.initialCapital.toLocaleString()}，使用上方市场数据，Binance图表已切换至${backtestSettings.symbol}`,
          type: 'success'
        })
        
        // 启动定时器，与上方数据刷新保持同步
        virtualTradingInterval.value = setInterval(() => {
          updateVirtualTradingWithRealData()
        }, 60000) // 每1分钟更新，与市场数据刷新同步
        
      } catch (error) {
        console.error('启动虚拟交易失败:', error)
        ElMessage({
          message: '启动虚拟交易失败: ' + error.message,
          type: 'error'
        })
        isVirtualTrading.value = false
      }
    }
    
    // 获取当前实时价格（优化版：优先使用Binance图表实时价格）
    const fetchCurrentRealTimePrice = async () => {
      try {
        // 检查网络状态
        if (!networkStatus.value.online) {
          throw new Error('网络连接不可用')
        }
        
        // 首先检查是否有Binance图表的实时价格数据（最高优先级）
        const currentVirtualSymbol = backtestSettings.symbol.replace('/', '')
        if (binanceSymbol.value === currentVirtualSymbol && binanceCurrentPrice.value > 0) {
          const price = binanceCurrentPrice.value
          const now = Date.now()
          
          virtualTradingResults.priceCache = price
          virtualTradingResults.cacheExpiry = now + 10000 // Binance图表数据更加实时，缓存10秒
          virtualTradingResults.currentPrice = price
          virtualTradingResults.lastUpdateTime = now
          
          // 添加到价格历史
          const nowDate = new Date(now)
          const priceData = {
            date: nowDate.toISOString().split('T')[0],
            time: nowDate.toLocaleTimeString(),
            close: price,
            timestamp: now
          }
          
          virtualTradingResults.priceHistory.push(priceData)
          
          // 保持最近100个价格数据点
          if (virtualTradingResults.priceHistory.length > 100) {
            virtualTradingResults.priceHistory = virtualTradingResults.priceHistory.slice(-100)
          }
          
          console.log(`⚡ 使用Binance图表实时价格: ${backtestSettings.symbol} = $${price.toFixed(2)}`)
          return price
        }
        
        // 其次使用上方市场概览中已获取的数据
        const currentOverview = marketOverview.find(item => item.name === backtestSettings.symbol)
        if (currentOverview && currentOverview.price !== '加载中...') {
          const price = parseFloat(currentOverview.price.replace(/,/g, ''))
          if (!isNaN(price) && price > 0) {
            const now = Date.now()
            virtualTradingResults.priceCache = price
            virtualTradingResults.cacheExpiry = now + 60000 // 使用已获取数据，缓存1分钟
            virtualTradingResults.currentPrice = price
            virtualTradingResults.lastUpdateTime = now
            
            // 添加到价格历史
            const nowDate = new Date(now)
            const priceData = {
              date: nowDate.toISOString().split('T')[0],
              time: nowDate.toLocaleTimeString(),
              close: price,
              timestamp: now
            }
            
            virtualTradingResults.priceHistory.push(priceData)
            
            // 保持最近100个价格数据点
            if (virtualTradingResults.priceHistory.length > 100) {
              virtualTradingResults.priceHistory = virtualTradingResults.priceHistory.slice(-100)
            }
            
            console.log(`✅ 使用市场概览数据: ${backtestSettings.symbol} = $${price}`)
            return price
          }
        }
        
        // 备用：尝试从比较数据中获取价格
        const symbolKey = backtestSettings.symbol
        const comparisonItem = comparisonData.find(item => item.symbol === symbolKey)
        if (comparisonItem) {
          // 优先使用Binance数据
          let price = null
          if (comparisonItem.binance && comparisonItem.binance.price !== '') {
            price = parseFloat(comparisonItem.binance.price.replace(/,/g, ''))
          } else if (comparisonItem.coingecko && comparisonItem.coingecko.price !== '') {
            price = parseFloat(comparisonItem.coingecko.price.replace(/,/g, ''))
          } else if (comparisonItem.cryptocompare && comparisonItem.cryptocompare.price !== '') {
            price = parseFloat(comparisonItem.cryptocompare.price.replace(/,/g, ''))
          }
          
          if (price && !isNaN(price) && price > 0) {
            const now = Date.now()
            virtualTradingResults.priceCache = price
            virtualTradingResults.cacheExpiry = now + 60000
            virtualTradingResults.currentPrice = price
            virtualTradingResults.lastUpdateTime = now
            
            console.log(`✅ 使用比较数据: ${symbolKey} = $${price}`)
            return price
          }
        }
        
        // 最后备用：如果以上数据都不可用，使用缓存数据
        if (virtualTradingResults.priceCache) {
          console.warn('✅ 使用缓存价格数据:', virtualTradingResults.priceCache)
          virtualTradingResults.currentPrice = virtualTradingResults.priceCache
          return virtualTradingResults.priceCache
        }
        
        throw new Error('无法从已有数据中获取价格，请等待数据更新')
        
      } catch (error) {
        console.warn('获取已有数据失败，尝试API备用方案:', error.message)
        
        // 紧急备用：直接调用API（仅在其他方式都失败时使用）
        return await fetchPriceFromAPI()
      }
    }
    
    // 紧急备用：直接API获取价格（仅在其他方式都失败时使用）
    const fetchPriceFromAPI = async () => {
      const symbolMap = {
        'BTC/USDT': 'BTCUSDT',
        'ETH/USDT': 'ETHUSDT', 
        'BNB/USDT': 'BNBUSDT',
        'SOL/USDT': 'SOLUSDT'
      }
      
      const binanceSymbol = symbolMap[backtestSettings.symbol]
      if (!binanceSymbol) {
        throw new Error(`不支持的交易对: ${backtestSettings.symbol}`)
      }
      
      try {
        const response = await axios.get('https://api.binance.com/api/v3/ticker/price', {
          params: { symbol: binanceSymbol },
          timeout: 5000
        })
        
        if (!response.data || !response.data.price) {
          throw new Error('无效的API响应数据')
        }
        
        const price = parseFloat(response.data.price)
        const now = Date.now()
        
        virtualTradingResults.priceCache = price
        virtualTradingResults.cacheExpiry = now + 8000
        virtualTradingResults.currentPrice = price
        virtualTradingResults.lastUpdateTime = now
        
        console.log(`⚠️ 紧急API获取: ${backtestSettings.symbol} = $${price}`)
        return price
        
      } catch (error) {
        console.error('紧急API也失败:', error.message)
        throw new Error('无法获取任何价格数据')
      }
    }
    
    // 使用实时数据更新虚拟交易（增强版：添加风险控制）
    const updateVirtualTradingWithRealData = async () => {
      try {
        // 获取最新价格
        await fetchCurrentRealTimePrice()
        
        // 更新账户信息
        updateVirtualAccount()
        
        // 立即保存状态（每次更新都保存）
        saveVirtualTradingState()
        
        // 检查风险控制状态
        if (backtestSettings.riskControl) {
          const riskCheck = checkRiskControl()
          if (!riskCheck.canTrade) {
            console.log('风险控制阻止交易:', riskCheck.reason)
            return
          }
        }
        
        // 检查止损止盈
        const stopOrder = checkStopLossAndTakeProfit()
        if (stopOrder) {
          executeVirtualTradeWithRealData(stopOrder)
          virtualTradingResults.lastSignalTime = Date.now()
          // 交易后立即保存状态
          saveVirtualTradingState()
          return
        }
        
        // 检查是否有足够的价格历史数据来计算技术指标
        if (virtualTradingResults.priceHistory.length < 20) {
          console.log(`正在积累价格数据... 当前: ${virtualTradingResults.priceHistory.length}/20`)
          return
        }
        
        // 防止频繁交易（30秒内不重复交易，避免过度交易）
        const now = Date.now()
        if (now - virtualTradingResults.lastSignalTime < 30000) {
          return
        }
        
        // 根据策略生成交易信号
        const signal = generateRealTimeVirtualTradingSignal()
        
        if (signal) {
          // 检查仓位限制
          if (signal.type === 'buy' && !checkPositionLimit()) {
            console.log('仓位限制阻止买入')
            return
          }
          
          executeVirtualTradeWithRealData(signal)
          virtualTradingResults.lastSignalTime = now
          
          // 在执行交易后立即保存状态
          saveVirtualTradingState()
        }
        
      } catch (error) {
        console.error('实时虚拟交易更新失败:', error)
        // 即使出错也保存当前状态
        saveVirtualTradingState()
      }
    }
    
    // 检查风险控制状态
    const checkRiskControl = () => {
      const currentDrawdownPercent = (virtualTradingResults.currentDrawdown / backtestSettings.initialCapital) * 100
      
      // 检查最大回撤限制
      if (currentDrawdownPercent > backtestSettings.maxDrawdownLimit) {
        if (!virtualTradingResults.riskLocked) {
          virtualTradingResults.riskLocked = true
          virtualTradingResults.riskEvents.push({
            type: 'MAX_DRAWDOWN_EXCEEDED',
            time: new Date().toLocaleString(),
            drawdown: currentDrawdownPercent,
            limit: backtestSettings.maxDrawdownLimit
          })
          
          ElNotification({
            title: '风险警告',
            message: `最大回撤超限（${currentDrawdownPercent.toFixed(2)}% > ${backtestSettings.maxDrawdownLimit}%），停止新的交易`,
            type: 'error',
            duration: 0 // 不自动关闭
          })
        }
        
        return {
          canTrade: false,
          reason: `最大回撤超限（${currentDrawdownPercent.toFixed(2)}%）`
        }
      }
      
      // 检查仓位集中度
      const positionPercent = (virtualTradingResults.positionValue / virtualTradingResults.totalValue) * 100
      if (positionPercent > backtestSettings.maxPosition) {
        return {
          canTrade: false,
          reason: `仓位过于集中（${positionPercent.toFixed(2)}%）`
        }
      }
      
      return { canTrade: true }
    }
    
    // 检查止损止盈
    const checkStopLossAndTakeProfit = () => {
      if (virtualTradingResults.position <= 0) return null
      
      const currentPrice = virtualTradingResults.currentPrice
      const lastBuyTrade = virtualTradingResults.trades.filter(t => t.type === 'buy').pop()
      
      if (!lastBuyTrade) return null
      
      const buyPrice = lastBuyTrade.price
      const stopLossPrice = buyPrice * (1 - backtestSettings.stopLoss / 100)
      const takeProfitPrice = buyPrice * (1 + backtestSettings.takeProfit / 100)
      
      // 检查止损
      if (currentPrice <= stopLossPrice) {
        virtualTradingResults.lastStopLoss = currentPrice
        return {
          type: 'sell',
          reason: `止损出局(价格: $${currentPrice.toFixed(2)}, 止损: $${stopLossPrice.toFixed(2)})`
        }
      }
      
      // 检查止盈
      if (currentPrice >= takeProfitPrice) {
        virtualTradingResults.lastTakeProfit = currentPrice
        return {
          type: 'sell',
          reason: `止盈出局(价格: $${currentPrice.toFixed(2)}, 止盈: $${takeProfitPrice.toFixed(2)})`
        }
      }
      
      return null
    }
    
    // 检查仓位限制
    const checkPositionLimit = () => {
      const tradePercent = backtestSettings.tradeAmount / 100
      const proposedTradeValue = virtualTradingResults.cash * tradePercent
      const currentPositionValue = virtualTradingResults.position * virtualTradingResults.currentPrice
      const totalPositionValue = currentPositionValue + proposedTradeValue
      const positionPercent = (totalPositionValue / virtualTradingResults.totalValue) * 100
      
      return positionPercent <= backtestSettings.maxPosition
    }
    const generateRealTimeVirtualTradingSignal = () => {
      const priceHistory = virtualTradingResults.priceHistory
      
      if (priceHistory.length < 20) return null
      
      // 根据选择的策略生成信号
      switch (backtestSettings.strategyType) {
        case 'ma_cross':
          return generateRealTimeMASignal(priceHistory)
        case 'rsi':
          return generateRealTimeRSISignal(priceHistory)
        case 'bollinger':
          return generateRealTimeBollingerSignal(priceHistory)
        case 'custom':
          return generateRealTimeCustomSignal(priceHistory)
        case 'ml_strategy1':
          return generateRealTimeMLStrategy1Signal(priceHistory)
        default:
          return null
      }
    }
    
    // 实时MA交叉信号
    const generateRealTimeMASignal = (priceHistory) => {
      const fastMA = backtestSettings.fastMAPeriod
      const slowMA = backtestSettings.slowMAPeriod
      
      if (priceHistory.length < slowMA) return null
      
      const prices = priceHistory.map(p => p.close)
      
      // 计算当前和上一个MA值
      const currentFastMA = prices.slice(-fastMA).reduce((a, b) => a + b, 0) / fastMA
      const currentSlowMA = prices.slice(-slowMA).reduce((a, b) => a + b, 0) / slowMA
      
      if (priceHistory.length < slowMA + 1) return null
      
      const prevFastMA = prices.slice(-(fastMA + 1), -1).reduce((a, b) => a + b, 0) / fastMA
      const prevSlowMA = prices.slice(-(slowMA + 1), -1).reduce((a, b) => a + b, 0) / slowMA
      
      // 金叉信号（买入）
      if (currentFastMA > currentSlowMA && prevFastMA <= prevSlowMA && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: 'MA金叉(实时)' }
      }
      
      // 死叉信号（卖出）
      if (currentFastMA < currentSlowMA && prevFastMA >= prevSlowMA && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: 'MA死叉(实时)' }
      }
      
      return null
    }
    
    // 实时RSI信号
    const generateRealTimeRSISignal = (priceHistory) => {
      const rsiPeriod = backtestSettings.rsiPeriod
      const overbought = backtestSettings.overbought
      const oversold = backtestSettings.oversold
      
      if (priceHistory.length < rsiPeriod + 1) return null
      
      // 计算RSI
      const prices = priceHistory.slice(-rsiPeriod - 1).map(p => p.close)
      let gains = 0, losses = 0
      
      for (let i = 1; i < prices.length; i++) {
        const change = prices[i] - prices[i - 1]
        if (change > 0) gains += change
        else losses += Math.abs(change)
      }
      
      const avgGain = gains / rsiPeriod
      const avgLoss = losses / rsiPeriod
      
      if (avgLoss === 0) return null
      
      const rs = avgGain / avgLoss
      const currentRSI = 100 - (100 / (1 + rs))
      
      // 计算前一个RSI
      const prevPrices = priceHistory.slice(-rsiPeriod - 2, -1).map(p => p.close)
      let prevGains = 0, prevLosses = 0
      
      for (let i = 1; i < prevPrices.length; i++) {
        const change = prevPrices[i] - prevPrices[i - 1]
        if (change > 0) prevGains += change
        else prevLosses += Math.abs(change)
      }
      
      const prevAvgGain = prevGains / rsiPeriod
      const prevAvgLoss = prevLosses / rsiPeriod
      const prevRS = prevAvgLoss === 0 ? 0 : prevAvgGain / prevAvgLoss
      const prevRSI = 100 - (100 / (1 + prevRS))
      
      // RSI从超卖区域上穿（买入）
      if (prevRSI <= oversold && currentRSI > oversold && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: `RSI超卖反弹(实时-${currentRSI.toFixed(1)})` }
      }
      
      // RSI从超买区域下穿（卖出）
      if (prevRSI >= overbought && currentRSI < overbought && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: `RSI超买回落(实时-${currentRSI.toFixed(1)})` }
      }
      
      return null
    }
    
    // 实时布林带信号
    const generateRealTimeBollingerSignal = (priceHistory) => {
      const bbPeriod = backtestSettings.bbPeriod
      const bbStdDev = backtestSettings.bbStdDev
      
      if (priceHistory.length < bbPeriod) return null
      
      const prices = priceHistory.slice(-bbPeriod).map(p => p.close)
      const middle = prices.reduce((a, b) => a + b, 0) / prices.length
      const stdDev = Math.sqrt(prices.map(x => Math.pow(x - middle, 2)).reduce((a, b) => a + b, 0) / prices.length)
      
      const upper = middle + (stdDev * bbStdDev)
      const lower = middle - (stdDev * bbStdDev)
      
      const currentPrice = priceHistory[priceHistory.length - 1].close
      
      // 价格触及下轨（买入）
      if (currentPrice <= lower && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: '价格触及布林带下轨(实时)' }
      }
      
      // 价格触及上轨（卖出）
      if (currentPrice >= upper && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: '价格触及布林带上轨(实时)' }
      }
      
      return null
    }
    
    // 实时自定义信号
    const generateRealTimeCustomSignal = (priceHistory) => {
      if (priceHistory.length < 5) return null
      
      const currentPrice = priceHistory[priceHistory.length - 1].close
      const recentPrices = priceHistory.slice(-5).map(p => p.close)
      const avgPrice = recentPrices.reduce((a, b) => a + b, 0) / 5
      
      // 价格突破平均线2%（买入）
      if (currentPrice > avgPrice * 1.02 && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: '价格突破(实时)' }
      }
      
      // 价格跌破平均线2%（卖出）
      if (currentPrice < avgPrice * 0.98 && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: '价格跌破止损(实时)' }
      }
      
      return null
    }
    
    // 执行实时虚拟交易
    const executeVirtualTradeWithRealData = (signal) => {
      const currentPrice = virtualTradingResults.currentPrice
      const tradePercent = backtestSettings.tradeAmount / 100
      const timestamp = new Date().toLocaleTimeString()
      const now = new Date()
      
      if (signal.type === 'buy' && virtualTradingResults.position === 0) {
        // 买入
        const tradeAmount = virtualTradingResults.cash * tradePercent
        const shares = tradeAmount / currentPrice
        
        virtualTradingResults.cash -= tradeAmount
        virtualTradingResults.position = shares
        
        const trade = {
          id: Date.now(),
          type: 'buy',
          price: currentPrice,
          amount: shares,
          value: tradeAmount,
          reason: signal.reason,
          time: timestamp,
          date: now.toISOString().split('T')[0],
          isRealTime: true
        }
        
        virtualTradingResults.trades.push(trade)
        
        // 增加当前会话交易计数
        virtualTradingResults.currentSessionTradesCount++
        
        // 交易后立即保存状态
        saveVirtualTradingState()
        
        ElNotification({
          title: '实时虚拟交易 - 买入',
          message: `${signal.reason} | 价格: $${currentPrice.toFixed(2)} | 数量: ${shares.toFixed(4)}`,
          type: 'success',
          duration: 4000
        })
        
      } else if (signal.type === 'sell' && virtualTradingResults.position > 0) {
        // 卖出
        const sellValue = virtualTradingResults.position * currentPrice
        const buyTrade = virtualTradingResults.trades.filter(t => t.type === 'buy').pop()
        const profit = buyTrade ? sellValue - (virtualTradingResults.position * buyTrade.price) : 0
        
        virtualTradingResults.cash += sellValue
        
        const trade = {
          id: Date.now(),
          type: 'sell',
          price: currentPrice,
          amount: virtualTradingResults.position,
          value: sellValue,
          profit: profit,
          reason: signal.reason,
          time: timestamp,
          date: now.toISOString().split('T')[0],
          isRealTime: true
        }
        
        virtualTradingResults.trades.push(trade)
        virtualTradingResults.position = 0
        
        // 增加当前会话交易计数
        virtualTradingResults.currentSessionTradesCount++
        
        // 交易后立即保存状态
        saveVirtualTradingState()
        
        ElNotification({
          title: '实时虚拟交易 - 卖出',
          message: `${signal.reason} | 价格: $${currentPrice.toFixed(2)} | 盈亏: $${profit.toFixed(2)}`,
          type: profit >= 0 ? 'success' : 'warning',
          duration: 4000
        })
      }
    }
    
    // 停止虚拟交易
    const stopVirtualTrading = () => {
      if (virtualTradingInterval.value) {
        clearInterval(virtualTradingInterval.value)
        virtualTradingInterval.value = null
      }
      
      // 保存当前状态在停止之前
      if (isVirtualTrading.value) {
        saveVirtualTradingState()
      }
      
      isVirtualTrading.value = false
      
      if (virtualTradingResults.trades.length > 0) {
        ElMessage({
          message: `虚拟交易已停止，总交易次数: ${virtualTradingResults.trades.length}，盈亏: ${virtualTradingResults.pnlPercent.toFixed(2)}%，状态已保存`,
          type: 'info',
          duration: 4000
        })
      } else {
        ElMessage({
          message: '虚拟交易已停止，状态已保存',
          type: 'info'
        })
      }
    }
    
    // 更新虚拟交易（已弃用，由updateVirtualTradingWithRealData替代）
    const updateVirtualTrading = () => {
      console.warn('updateVirtualTrading已弃用，虚拟交易现在使用实时数据')
      // 这个函数保留用于兼容性，但不再使用历史数据
      // 实际的虚拟交易逻辑已移动到updateVirtualTradingWithRealData
    }
    
    // 生成虚拟交易信号
    const generateVirtualTradingSignal = () => {
      const currentIndex = virtualCurrentIndex.value
      const data = virtualTradingData.value
      
      if (currentIndex < 20) return null // 需要足够的历史数据
      
      // 根据选择的策略生成信号
      switch (backtestSettings.strategyType) {
        case 'ma_cross':
          return generateMASignal(data, currentIndex)
        case 'rsi':
          return generateRSISignal(data, currentIndex)
        case 'bollinger':
          return generateBollingerSignal(data, currentIndex)
        case 'custom':
          return generateCustomSignal(data, currentIndex)
        case 'ml_strategy1':
          return generateMLStrategy1Signal(data, currentIndex)
        default:
          return null
      }
    }
    
    // MA交叉信号
    const generateMASignal = (data, currentIndex) => {
      const fastMA = backtestSettings.fastMAPeriod
      const slowMA = backtestSettings.slowMAPeriod
      
      if (currentIndex < slowMA) return null
      
      // 计算当前和上一个MA值
      const currentFastMA = calculateMA(data.slice(currentIndex - fastMA + 1, currentIndex + 1), fastMA)[0]
      const currentSlowMA = calculateMA(data.slice(currentIndex - slowMA + 1, currentIndex + 1), slowMA)[0]
      const prevFastMA = calculateMA(data.slice(currentIndex - fastMA, currentIndex), fastMA)[0]
      const prevSlowMA = calculateMA(data.slice(currentIndex - slowMA, currentIndex), slowMA)[0]
      
      // 金叉信号（买入）
      if (currentFastMA > currentSlowMA && prevFastMA <= prevSlowMA && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: 'MA金叉' }
      }
      
      // 死叉信号（卖出）
      if (currentFastMA < currentSlowMA && prevFastMA >= prevSlowMA && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: 'MA死叉' }
      }
      
      return null
    }
    
    // RSI信号
    const generateRSISignal = (data, currentIndex) => {
      const rsiPeriod = backtestSettings.rsiPeriod
      const overbought = backtestSettings.overbought
      const oversold = backtestSettings.oversold
      
      if (currentIndex < rsiPeriod + 1) return null
      
      const rsiData = data.slice(Math.max(0, currentIndex - rsiPeriod - 10), currentIndex + 1)
      const rsiValues = calculateRSI(rsiData, rsiPeriod)
      
      if (rsiValues.length < 2) return null
      
      const currentRSI = rsiValues[rsiValues.length - 1]
      const prevRSI = rsiValues[rsiValues.length - 2]
      
      // RSI从超卖区域上穿（买入）
      if (prevRSI <= oversold && currentRSI > oversold && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: `RSI超卖反弹(${currentRSI.toFixed(1)})` }
      }
      
      // RSI从超买区域下穿（卖出）
      if (prevRSI >= overbought && currentRSI < overbought && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: `RSI超买回落(${currentRSI.toFixed(1)})` }
      }
      
      return null
    }
    
    // 布林带信号
    const generateBollingerSignal = (data, currentIndex) => {
      const bbPeriod = backtestSettings.bbPeriod
      const bbStdDev = backtestSettings.bbStdDev
      
      if (currentIndex < bbPeriod) return null
      
      const recentData = data.slice(currentIndex - bbPeriod + 1, currentIndex + 1)
      const prices = recentData.map(d => d.close)
      const middle = prices.reduce((a, b) => a + b, 0) / prices.length
      const stdDev = Math.sqrt(prices.map(x => Math.pow(x - middle, 2)).reduce((a, b) => a + b, 0) / prices.length)
      
      const upper = middle + (stdDev * bbStdDev)
      const lower = middle - (stdDev * bbStdDev)
      
      const currentPrice = data[currentIndex].close
      
      // 价格触及下轨（买入）
      if (currentPrice <= lower && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: '价格触及布林带下轨' }
      }
      
      // 价格触及上轨（卖出）
      if (currentPrice >= upper && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: '价格触及布林带上轨' }
      }
      
      return null
    }
    
    // 自定义信号
    const generateCustomSignal = (data, currentIndex) => {
      // 简单的价格突破策略
      if (currentIndex < 5) return null
      
      const currentPrice = data[currentIndex].close
      const currentVolume = data[currentIndex].volume
      const recentData = data.slice(currentIndex - 5, currentIndex)
      const avgPrice = recentData.reduce((sum, d) => sum + d.close, 0) / 5
      const avgVolume = recentData.reduce((sum, d) => sum + d.volume, 0) / 5
      
      // 价格突破 + 成交量放大（买入）
      if (currentPrice > avgPrice * 1.02 && currentVolume > avgVolume * 1.5 && virtualTradingResults.position === 0) {
        return { type: 'buy', reason: '价格突破+量能放大' }
      }
      
      // 价格跌破（卖出）
      if (currentPrice < avgPrice * 0.98 && virtualTradingResults.position > 0) {
        return { type: 'sell', reason: '价格跌破止损' }
      }
      
      return null
    }
    
    // 执行虚拟交易
    const executeVirtualTrade = (signal, currentData) => {
      const currentPrice = currentData.close
      const tradePercent = backtestSettings.tradeAmount / 100
      const timestamp = new Date().toLocaleTimeString()
      
      if (signal.type === 'buy' && virtualTradingResults.position === 0) {
        // 买入
        const tradeAmount = virtualTradingResults.cash * tradePercent
        const shares = tradeAmount / currentPrice
        
        virtualTradingResults.cash -= tradeAmount
        virtualTradingResults.position = shares
        
        const trade = {
          id: Date.now(),
          type: 'buy',
          price: currentPrice,
          amount: shares,
          value: tradeAmount,
          reason: signal.reason,
          time: timestamp,
          date: currentData.date
        }
        
        virtualTradingResults.trades.push(trade)
        
        ElNotification({
          title: '虚拟交易 - 买入',
          message: `${signal.reason} | 价格: $${currentPrice.toFixed(2)} | 数量: ${shares.toFixed(4)}`,
          type: 'success',
          duration: 3000
        })
        
      } else if (signal.type === 'sell' && virtualTradingResults.position > 0) {
        // 卖出
        const sellValue = virtualTradingResults.position * currentPrice
        const buyTrade = virtualTradingResults.trades.filter(t => t.type === 'buy').pop()
        const profit = buyTrade ? sellValue - (virtualTradingResults.position * buyTrade.price) : 0
        
        virtualTradingResults.cash += sellValue
        
        const trade = {
          id: Date.now(),
          type: 'sell',
          price: currentPrice,
          amount: virtualTradingResults.position,
          value: sellValue,
          profit: profit,
          reason: signal.reason,
          time: timestamp,
          date: currentData.date
        }
        
        virtualTradingResults.trades.push(trade)
        virtualTradingResults.position = 0
        
        ElNotification({
          title: '虚拟交易 - 卖出',
          message: `${signal.reason} | 价格: $${currentPrice.toFixed(2)} | 盈亏: $${profit.toFixed(2)}`,
          type: profit >= 0 ? 'success' : 'warning',
          duration: 3000
        })
      }
    }
    
    // 搬砖套利相关变量
    const arbitrageSymbol = ref('BTC/USDT')
    const isArbitrageMonitoring = ref(false)
    const arbitrageOpportunity = ref(null)
    const binanceArbitragePrice = ref(0)
    const okxArbitragePrice = ref(0)
    const binanceChange = ref(0)
    const okxChange = ref(0)
    const arbitrageSpread = ref(0)
    const arbitrageValue = ref(0)
    const arbitrageFee = ref(0)
    const arbitrageHistory = ref([])
    const arbitrageThreshold = ref(0.5) // 套利阈值（百分比）
    const tradeAmount = ref(1) // 交易数量
    const arbitrageUpdateInterval = ref(10000) // 更新间隔（毫秒）
    const arbitrageFeeRate = ref(0.001) // 手续费率（0.1%）
    let arbitrageIntervalId = null // 定时器ID
    let arbitrageStartTime = null // 监控开始时间
    
    // 套利统计信息
    const arbitrageStats = reactive({
      totalOpportunities: 0, // 总套利机会次数
      successfulTrades: 0, // 成功套利次数
      totalProfit: 0, // 总利润
      avgSpread: 0, // 平均价差
      maxSpread: 0, // 最大价差
      monitoringTime: 0, // 监控时长（秒）
      spreadSum: 0, // 价差总和（用于计算平均值）
      spreadCount: 0, // 价差计数（用于计算平均值）
      successRate: 0, // 成功率
      minProfitThreshold: 0.5, // 最小利润阈值（美元）
      totalFees: 0 // 总手续费
    })
    
    // 格式化持续时间
    const formatDuration = (seconds) => {
      // 确保seconds是有效数字
      const validSeconds = typeof seconds === 'number' && !isNaN(seconds) ? Math.floor(seconds) : 0;
      
      const hrs = Math.floor(validSeconds / 3600)
      const mins = Math.floor((validSeconds % 3600) / 60)
      const secs = validSeconds % 60
      return `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }
    
    // 重置统计信息
    const resetArbitrageStats = () => {
      arbitrageStats.totalOpportunities = 0
      arbitrageStats.successfulTrades = 0
      arbitrageStats.totalProfit = 0
      arbitrageStats.avgSpread = 0
      arbitrageStats.maxSpread = 0
      arbitrageStats.monitoringTime = 0
      arbitrageStats.spreadSum = 0
      arbitrageStats.spreadCount = 0
      arbitrageStats.successRate = 0
      arbitrageStats.totalFees = 0
    }
    
    // 更新统计信息
    const updateArbitrageStats = (spread, profit, fees) => {
      // 确保spread和profit是有效数字
      const validSpread = typeof spread === 'number' && !isNaN(spread) ? Math.abs(spread) : 0;
      const validProfit = typeof profit === 'number' && !isNaN(profit) ? profit : 0;
      const validFees = typeof fees === 'number' && !isNaN(fees) ? fees : 0;
      
      // 更新价差统计
      arbitrageStats.spreadSum += validSpread;
      arbitrageStats.spreadCount++;
      arbitrageStats.avgSpread = arbitrageStats.spreadCount > 0 ? arbitrageStats.spreadSum / arbitrageStats.spreadCount : 0;
      arbitrageStats.maxSpread = Math.max(arbitrageStats.maxSpread, validSpread);
      
      // 更新套利机会统计
      arbitrageStats.totalOpportunities++;
      
      // 更新手续费统计
      arbitrageStats.totalFees += validFees;
      
      // 如果有利润且超过阈值，更新成功交易和总利润
      if (validProfit > 0 && validProfit >= arbitrageStats.minProfitThreshold) {
        arbitrageStats.successfulTrades++;
        arbitrageStats.totalProfit += validProfit;
      }
      
      // 更新成功率
      arbitrageStats.successRate = arbitrageStats.totalOpportunities > 0 
        ? (arbitrageStats.successfulTrades / arbitrageStats.totalOpportunities) * 100 
        : 0;
    }
    
    // 计算套利机会的预期收益
    const calculateExpectedProfit = (binancePrice, okxPrice, amount, feeRate) => {
      const spread = ((okxPrice - binancePrice) / binancePrice) * 100;
      const grossProfit = Math.abs(okxPrice - binancePrice) * amount;
      const fees = (binancePrice * amount * feeRate) + (okxPrice * amount * feeRate);
      const netProfit = grossProfit - fees;
      
      return {
        spread: spread,
        grossProfit: grossProfit,
        fees: fees,
        netProfit: netProfit,
        isProfitable: netProfit > arbitrageStats.minProfitThreshold
      };
    }
    
    // 风险评估函数
    const evaluateArbitrageRisk = (binancePrice, okxPrice, amount, feeRate) => {
      // 计算预期收益
      const expected = calculateExpectedProfit(binancePrice, okxPrice, amount, feeRate);
      
      // 风险因素评估
      const riskFactors = {
        // 价差风险
        spreadRisk: expected.spread < 0.1 ? 'high' : expected.spread < 0.3 ? 'medium' : 'low',
        // 手续费风险
        feeRisk: expected.fees > expected.grossProfit * 0.5 ? 'high' : 
                 expected.fees > expected.grossProfit * 0.3 ? 'medium' : 'low',
        // 利润风险
        profitRisk: expected.netProfit < arbitrageStats.minProfitThreshold * 2 ? 'high' : 
                    expected.netProfit < arbitrageStats.minProfitThreshold * 5 ? 'medium' : 'low',
        // 市场风险
        marketRisk: Math.abs(binancePrice - okxPrice) / ((binancePrice + okxPrice) / 2) > 0.05 ? 'high' : 'low'
      };
      
      // 综合风险评估
      const highRisks = Object.values(riskFactors).filter(risk => risk === 'high').length;
      const mediumRisks = Object.values(riskFactors).filter(risk => risk === 'medium').length;
      
      let overallRisk = 'low';
      if (highRisks >= 2) overallRisk = 'high';
      else if (highRisks >= 1 || mediumRisks >= 2) overallRisk = 'medium';
      
      return {
        riskFactors,
        overallRisk,
        isAcceptable: overallRisk !== 'high' && expected.isProfitable
      };
    }
    
    // 更新监控时长
    const updateMonitoringTime = () => {
      if (arbitrageStartTime) {
        const now = new Date()
        arbitrageStats.monitoringTime = Math.floor((now - arbitrageStartTime) / 1000)
      }
    }
    
    // 更新搬砖套利数据
    const updateArbitrageData = async () => {
      try {
        // 获取Binance价格
        const binanceResponse = await axios.get('https://api.binance.com/api/v3/ticker/24hr', {
          params: { symbol: arbitrageSymbol.value.replace('/', '') }
        })
        
        binanceArbitragePrice.value = parseFloat(binanceResponse.data.lastPrice) || 0;
        binanceChange.value = parseFloat(binanceResponse.data.priceChangePercent) || 0;
        
        // 获取OKX价格
        const okxSymbolFormat = arbitrageSymbol.value.replace('/', '-').toLowerCase()
        const okxResponse = await axios.get('https://www.okx.com/api/v5/market/ticker', {
          params: { instId: okxSymbolFormat.toUpperCase() }
        })
        
        if (okxResponse.data && okxResponse.data.data && okxResponse.data.data[0]) {
          okxArbitragePrice.value = parseFloat(okxResponse.data.data[0].last) || 0;
          // OKX没有直接提供24小时变化，我们简单计算一下
          const open24h = parseFloat(okxResponse.data.data[0].open24h) || 0;
          if (open24h > 0) {
            okxChange.value = ((okxArbitragePrice.value - open24h) / open24h) * 100 || 0;
          } else {
            okxChange.value = 0;
          }
        } else {
          // 如果OKX数据获取失败，设置默认值
          okxArbitragePrice.value = 0;
          okxChange.value = 0;
        }
        
        // 计算价差
        if (binanceArbitragePrice.value > 0 && okxArbitragePrice.value > 0) {
          // 假设从Binance买入，OKX卖出
          const spread = ((okxArbitragePrice.value - binanceArbitragePrice.value) / binanceArbitragePrice.value) * 100;
          arbitrageSpread.value = isNaN(spread) ? 0 : spread;
          
          // 计算套利价值（根据设定的交易数量）
          arbitrageValue.value = Math.abs(okxArbitragePrice.value - binanceArbitragePrice.value) * tradeAmount.value;
          
          // 估算手续费（使用可配置的手续费率）
          const binanceFee = binanceArbitragePrice.value * tradeAmount.value * arbitrageFeeRate.value;
          const okxFee = okxArbitragePrice.value * tradeAmount.value * arbitrageFeeRate.value;
          arbitrageFee.value = (binanceFee + okxFee) || 0;
          
          // 更新统计信息
          updateArbitrageStats(arbitrageSpread.value, arbitrageValue.value - arbitrageFee.value, arbitrageFee.value);
          
          // 检查是否有套利机会
          if (arbitrageSpread.value > arbitrageThreshold.value && 
              (arbitrageValue.value - arbitrageFee.value) >= arbitrageStats.minProfitThreshold) { // 使用可配置的阈值和最小利润
            const profit = arbitrageValue.value - arbitrageFee.value;
            
            arbitrageOpportunity.value = {
              spread: arbitrageSpread.value,
              binancePrice: binanceArbitragePrice.value,
              okxPrice: okxArbitragePrice.value,
              value: arbitrageValue.value,
              fee: arbitrageFee.value,
              profit: profit,
              time: new Date().toLocaleString()
            }
            
            // 添加到历史记录
            arbitrageHistory.value.unshift({
              time: new Date().toLocaleString(),
              symbol: arbitrageSymbol.value,
              binancePrice: binanceArbitragePrice.value,
              okxPrice: okxArbitragePrice.value,
              spread: arbitrageSpread.value,
              profit: profit,
              fee: arbitrageFee.value
            })
            
            // 保持历史记录在50条以内
            if (arbitrageHistory.value.length > 50) {
              arbitrageHistory.value = arbitrageHistory.value.slice(0, 50)
            }
            
            // 显示套利机会通知
            if (profit > 0) {
              ElNotification({
                title: '套利机会',
                message: `${arbitrageSymbol.value} 存在套利机会，价差: ${arbitrageSpread.value.toFixed(2)}%，预计利润: $${profit.toFixed(2)}`,
                type: 'success',
                duration: 5000
              })
            }
          } else {
            arbitrageOpportunity.value = null
          }
        } else {
          // 如果价格数据无效，重置相关值
          arbitrageSpread.value = 0;
          arbitrageValue.value = 0;
          arbitrageFee.value = 0;
          arbitrageOpportunity.value = null;
        }
      } catch (error) {
        console.error('更新搬砖套利数据失败:', error)
        ElMessage({
          message: '获取套利数据失败: ' + error.message,
          type: 'error'
        })
        
        // 出错时重置相关值
        arbitrageSpread.value = 0;
        arbitrageValue.value = 0;
        arbitrageFee.value = 0;
        arbitrageOpportunity.value = null;
      }
    }
    
    // 开始/停止搬砖套利监控
    const startArbitrageMonitoring = () => {
      // 切换监控状态
      isArbitrageMonitoring.value = !isArbitrageMonitoring.value
      
      if (isArbitrageMonitoring.value) {
        // 重置统计信息并记录开始时间
        resetArbitrageStats()
        arbitrageStartTime = new Date()
        
        // 立即更新一次数据
        updateArbitrageData().then(() => {
          // 成功更新后的处理
        }).catch(error => {
          console.error('初始更新套利数据失败:', error)
          ElMessage({
            message: '初始更新套利数据失败: ' + error.message,
            type: 'error'
          })
        })
        
        // 根据设定的间隔更新数据
        if (arbitrageIntervalId) {
          clearInterval(arbitrageIntervalId)
        }
        
        arbitrageIntervalId = setInterval(() => {
          if (isArbitrageMonitoring.value) {
            updateArbitrageData().then(() => {
              // 成功更新后的处理
            }).catch(error => {
              console.error('定时更新套利数据失败:', error)
              ElMessage({
                message: '定时更新套利数据失败: ' + error.message,
                type: 'error'
              })
            })
            updateMonitoringTime()
          }
        }, arbitrageUpdateInterval.value)
        
        ElMessage({
          message: '搬砖套利监控已启动',
          type: 'success'
        })
      } else {
        // 停止监控
        if (arbitrageIntervalId) {
          clearInterval(arbitrageIntervalId)
          arbitrageIntervalId = null
        }
        arbitrageStartTime = null
        
        ElMessage({
          message: '搬砖套利监控已停止',
          type: 'info'
        })
      }
    }
    
    // 更改更新间隔
    const changeUpdateInterval = (value) => {
      if (isArbitrageMonitoring.value) {
        // 如果正在监控，重新设置定时器
        if (arbitrageIntervalId) {
          clearInterval(arbitrageIntervalId)
        }
        arbitrageIntervalId = setInterval(() => {
          if (isArbitrageMonitoring.value) {
            updateArbitrageData()
            updateMonitoringTime()
          }
        }, value)
      }
    }
    
    // 导出套利历史记录
    const exportArbitrageHistory = () => {
      if (!arbitrageHistory.value || arbitrageHistory.value.length === 0) {
        ElMessage({
          message: '没有套利历史记录可导出',
          type: 'warning'
        })
        return
      }
      
      try {
        // 准备导出数据
        const exportData = {
          summary: {
            symbol: arbitrageSymbol.value,
            totalOpportunities: arbitrageStats.totalOpportunities,
            successfulTrades: arbitrageStats.successfulTrades,
            totalProfit: arbitrageStats.totalProfit,
            avgSpread: arbitrageStats.avgSpread,
            maxSpread: arbitrageStats.maxSpread,
            successRate: arbitrageStats.successRate,
            totalFees: arbitrageStats.totalFees,
            netProfit: arbitrageStats.totalProfit,
            exportTime: new Date().toISOString(),
            timePeriod: {
              start: arbitrageHistory.value.length > 0 ? arbitrageHistory.value[arbitrageHistory.value.length - 1].time : 'N/A',
              end: arbitrageHistory.value.length > 0 ? arbitrageHistory.value[0].time : 'N/A'
            }
          },
          history: arbitrageHistory.value.map(item => ({
            time: item.time,
            symbol: item.symbol,
            binancePrice: item.binancePrice,
            okxPrice: item.okxPrice,
            spread: item.spread,
            profit: item.profit,
            fee: item.fee
          }))
        }
        
        // 生成文件名
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-').substring(0, 19)
        const filename = `arbitrage_history_${arbitrageSymbol.value.replace('/', '')}_${timestamp}`
        
        // 导出JSON格式
        const jsonContent = JSON.stringify(exportData, null, 2)
        downloadFile(jsonContent, `${filename}.json`, 'application/json')
        
        // 导出CSV格式
        const csvContent = generateArbitrageCSV(exportData.history)
        downloadFile(csvContent, `${filename}_history.csv`, 'text/csv')
        
        ElMessage({
          message: `套利历史记录已导出（JSON + CSV）`,
          type: 'success',
          duration: 3000
        })
        
      } catch (error) {
        console.error('导出套利历史记录失败:', error)
        ElMessage({
          message: '导出套利历史记录失败: ' + error.message,
          type: 'error'
        })
      }
    }
    

    
    // 清空历史记录
    const clearArbitrageHistory = () => {
      ElMessageBox.confirm(
        '确定要清空所有套利历史记录吗？此操作不可恢复。',
        '清空历史记录',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        arbitrageHistory.value = []
        ElMessage({
          message: '套利历史记录已清空',
          type: 'success'
        })
      }).catch(() => {
        // 用户取消操作
      })
    }
    

    
    // 计算移动平均线
    const calculateMA = (data, period) => {
      const ma = []
      for (let i = period - 1; i < data.length; i++) {
        let sum = 0
        for (let j = 0; j < period; j++) {
          sum += data[i - j].close
        }
        ma.push(sum / period)
      }
      return ma
    }
    
    // RSI策略
    const runRSIStrategy = (data) => {
      const results = {
        equityCurve: [],
        trades: []
      }
      
      const capital = backtestSettings.initialCapital
      const tradePercent = backtestSettings.tradeAmount / 100
      const rsiPeriod = backtestSettings.rsiPeriod
      const overbought = backtestSettings.overbought
      const oversold = backtestSettings.oversold
      const stopLoss = backtestSettings.stopLoss / 100
      const takeProfit = backtestSettings.takeProfit / 100
      
      let position = 0
      let cash = capital
      let lastBuyPrice = 0
      
      // 计算RSI
      const rsiValues = calculateRSI(data, rsiPeriod)
      
      if (rsiValues.length === 0) {
        console.warn('RSI计算失败，数据不足')
        return results
      }
      
      for (let i = 1; i < rsiValues.length; i++) {
        const dataIndex = i + rsiPeriod
        if (dataIndex >= data.length) break
        
        const currentPrice = data[dataIndex].close
        const currentDate = data[dataIndex].date
        const currentRSI = rsiValues[i]
        const prevRSI = rsiValues[i-1]
        
        // RSI交易信号
        const buySignal = prevRSI <= oversold && currentRSI > oversold && position === 0
        const sellSignal = prevRSI >= overbought && currentRSI < overbought && position > 0
        
        // 检查止损止盈
        const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
        const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
        
        if (buySignal && cash > 0) {
          // 买入
          const tradeValue = cash * tradePercent
          const amount = tradeValue / currentPrice
          position = amount
          cash -= tradeValue
          lastBuyPrice = currentPrice
          
          results.trades.push({
            date: currentDate,
            type: 'buy',
            price: currentPrice,
            amount: amount,
            value: tradeValue
          })
        } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
          // 卖出
          const sellAmount = position
          const tradeValue = sellAmount * currentPrice
          const profit = tradeValue - (sellAmount * lastBuyPrice)
          cash += tradeValue
          position = 0
          
          results.trades.push({
            date: currentDate,
            type: 'sell',
            price: currentPrice,
            amount: sellAmount,
            value: tradeValue,
            profit: profit
          })
        }
        
        // 更新权益曲线
        const totalEquity = cash + (position * currentPrice)
        results.equityCurve.push({
          date: currentDate,
          equity: totalEquity
        })
      }
      
      return results
    }
    
    // 计算RSI
    const calculateRSI = (data, period) => {
      if (data.length < period + 1) return []
      
      const rsi = []
      const gains = []
      const losses = []
      
      // 计算每日涨跌
      for (let i = 1; i < data.length; i++) {
        const change = data[i].close - data[i-1].close
        gains.push(change > 0 ? change : 0)
        losses.push(change < 0 ? Math.abs(change) : 0)
      }
      
      // 计算初始平均值
      let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period
      let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period
      
      for (let i = period; i < gains.length; i++) {
        const rs = avgLoss === 0 ? 100 : avgGain / avgLoss
        const rsiValue = 100 - (100 / (1 + rs))
        rsi.push(rsiValue)
        
        // 更新平均值（使用指数平滑）
        avgGain = (avgGain * (period - 1) + gains[i]) / period
        avgLoss = (avgLoss * (period - 1) + losses[i]) / period
      }
      
      return rsi
    }
    
    // 布林带策略
    const runBollingerStrategy = (data) => {
      const results = {
        equityCurve: [],
        trades: []
      }
      
      const capital = backtestSettings.initialCapital
      const tradePercent = backtestSettings.tradeAmount / 100
      const bbPeriod = backtestSettings.bbPeriod
      const bbStdDev = backtestSettings.bbStdDev
      const stopLoss = backtestSettings.stopLoss / 100
      const takeProfit = backtestSettings.takeProfit / 100
      
      let position = 0
      let cash = capital
      let lastBuyPrice = 0
      
      // 计算布林带
      const bollingerBands = calculateBollingerBands(data, bbPeriod, bbStdDev)
      
      if (bollingerBands.length === 0) {
        console.warn('布林带计算失败，数据不足')
        return results
      }
      
      for (let i = 0; i < bollingerBands.length; i++) {
        const dataIndex = i + bbPeriod - 1
        if (dataIndex >= data.length) break
        
        const currentPrice = data[dataIndex].close
        const currentDate = data[dataIndex].date
        const { upper, lower, middle } = bollingerBands[i]
        
        // 布林带交易信号
        const buySignal = currentPrice <= lower && position === 0  // 价格触及下轨
        const sellSignal = currentPrice >= upper && position > 0   // 价格触及上轨
        
        // 检查止损止盈
        const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
        const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
        
        if (buySignal && cash > 0) {
          // 买入
          const tradeValue = cash * tradePercent
          const amount = tradeValue / currentPrice
          position = amount
          cash -= tradeValue
          lastBuyPrice = currentPrice
          
          results.trades.push({
            date: currentDate,
            type: 'buy',
            price: currentPrice,
            amount: amount,
            value: tradeValue
          })
        } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
          // 卖出
          const sellAmount = position
          const tradeValue = sellAmount * currentPrice
          const profit = tradeValue - (sellAmount * lastBuyPrice)
          cash += tradeValue
          position = 0
          
          results.trades.push({
            date: currentDate,
            type: 'sell',
            price: currentPrice,
            amount: sellAmount,
            value: tradeValue,
            profit: profit
          })
        }
        
        // 更新权益曲线
        const totalEquity = cash + (position * currentPrice)
        results.equityCurve.push({
          date: currentDate,
          equity: totalEquity
        })
      }
      
      return results
    }
    
    // 计算布林带
    const calculateBollingerBands = (data, period, stdDevMultiplier) => {
      if (data.length < period) return []
      
      const bands = []
      
      for (let i = period - 1; i < data.length; i++) {
        // 计算中轨（移动平均线）
        let sum = 0
        for (let j = 0; j < period; j++) {
          sum += data[i - j].close
        }
        const middle = sum / period
        
        // 计算标准差
        let variance = 0
        for (let j = 0; j < period; j++) {
          const diff = data[i - j].close - middle
          variance += diff * diff
        }
        const stdDev = Math.sqrt(variance / period)
        
        // 计算上下轨
        const upper = middle + (stdDev * stdDevMultiplier)
        const lower = middle - (stdDev * stdDevMultiplier)
        
        bands.push({ upper, middle, lower })
      }
      
      return bands
    }
    
    // AI智能策略1 - 基于机器学习的多因子量化交易策略（优化版）
    const runMLStrategy1 = (data) => {
      const results = {
        equityCurve: [],
        trades: [],
        signals: [], // 新增：记录信号强度
        performance: {} // 新增：性能指标
      }
      
      const capital = backtestSettings.initialCapital
      const baseTradePercent = backtestSettings.tradeAmount / 100
      
      let position = 0
      let cash = capital
      let lastBuyPrice = 0
      let marketState = 'neutral'
      let consecutiveLosses = 0 // 新增：连续亏损计数
      let maxEquity = capital // 新增：最高权益记录
      
      const minDataPoints = Math.max(100, data.length * 0.15) // 优化：增加最小数据点
      
      for (let i = Math.floor(minDataPoints); i < data.length; i++) {
        const currentPrice = data[i].close
        const currentDate = data[i].date
        
        const features = calculateMLFeatures(data, i)
        if (!features) continue
        
        if (backtestSettings.mlMarketStateAware) {
          marketState = identifyMarketState(data, i)
        }
        
        const mlPrediction = performMLPrediction(features, marketState)
        
        // 记录信号强度用于分析
        results.signals.push({
          date: currentDate,
          signal: mlPrediction.signal,
          confidence: mlPrediction.confidence,
          marketState: marketState,
          price: currentPrice
        })
        
        let dynamicTradePercent = baseTradePercent
        if (backtestSettings.mlDynamicPositioning) {
          dynamicTradePercent = calculateDynamicPosition(features, mlPrediction, baseTradePercent, consecutiveLosses)
        }
        
        const adaptiveStopLoss = calculateAdaptiveStopLoss(features.atr, backtestSettings.mlAdaptiveStopLoss)
        const adaptiveTakeProfit = calculateAdaptiveTakeProfit(features.atr, mlPrediction.confidence)
        
        // 优化：添加风险过滤器
        const riskFilter = evaluateRiskConditions(features, marketState, consecutiveLosses, cash, capital)
        
        const buySignal = mlPrediction.signal === 'buy' && 
                         mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
                         position === 0 && 
                         riskFilter.allowBuy // 新增风险过滤
        
        const sellSignal = (mlPrediction.signal === 'sell' && 
                           mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold) ||
                          checkMLStopConditions(currentPrice, lastBuyPrice, adaptiveStopLoss, adaptiveTakeProfit) ||
                          riskFilter.forceSell // 新增强制卖出条件
        
        if (buySignal && cash > 0) {
          const tradeValue = cash * (dynamicTradePercent / 100)
          const amount = tradeValue / currentPrice
          position = amount
          cash -= tradeValue
          lastBuyPrice = currentPrice
          consecutiveLosses = 0 // 重置连续亏损计数
          
          results.trades.push({
            date: currentDate,
            type: 'buy',
            price: currentPrice,
            amount: amount,
            value: tradeValue,
            reason: `ML信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState},动态仓位:${dynamicTradePercent.toFixed(1)}%)`
          })
        } else if (sellSignal && position > 0) {
          const sellAmount = position
          const tradeValue = sellAmount * currentPrice
          const profit = tradeValue - (sellAmount * lastBuyPrice)
          cash += tradeValue
          position = 0
          
          // 更新连续亏损计数
          if (profit < 0) {
            consecutiveLosses++
          } else {
            consecutiveLosses = 0
          }
          
          const sellReason = mlPrediction.signal === 'sell' ? 
            `ML卖出信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%)` :
            riskFilter && riskFilter.forceSell ? '风险控制强制卖出' :
            `智能止损止盈(ATR:${features.atr.toFixed(2)})`
          
          results.trades.push({
            date: currentDate,
            type: 'sell',
            price: currentPrice,
            amount: sellAmount,
            value: tradeValue,
            profit: profit,
            reason: sellReason
          })
        }
        
        const totalEquity = cash + (position * currentPrice)
        
        // 更新最高权益
        if (totalEquity > maxEquity) {
          maxEquity = totalEquity
        }
        
        results.equityCurve.push({
          date: currentDate,
          equity: totalEquity,
          drawdown: ((maxEquity - totalEquity) / maxEquity * 100).toFixed(2) // 记录回撤
        })
      }
      
      // 计算策略性能指标
      results.performance = calculateStrategyPerformance(results)
      
      return results
    }
    
    // ML特征计算函数
    const calculateMLFeatures = (data, index) => {
      if (index < 50) return null
      
      const currentData = data.slice(Math.max(0, index - 49), index + 1)
      const prices = currentData.map(d => d.close)
      const volumes = currentData.map(d => d.volume)
      const highs = currentData.map(d => d.high)
      const lows = currentData.map(d => d.low)
      
      const ma5 = calculateSMA(prices, 5)
      const ma10 = calculateSMA(prices, 10)
      const ma20 = calculateSMA(prices, 20)
      const ma50 = calculateSMA(prices, 50)
      
      const rsi = calculateRSI(currentData, 14)
      const macd = calculateMACD(prices)
      const bb = calculateBB(prices, 20, 2)
      const atr = calculateATR(currentData, 14)
      
      const volumeMA = calculateSMA(volumes, 20)
      const volumeRatio = volumes[volumes.length - 1] / (volumeMA[volumeMA.length - 1] || 1)
      
      const momentum = (prices[prices.length - 1] - prices[prices.length - 10]) / prices[prices.length - 10]
      const volatility = calculateVolatility(prices, 20)
      const supportResistance = calculateSupportResistance(currentData)
      
      return {
        price: prices[prices.length - 1],
        ma5: ma5[ma5.length - 1],
        ma10: ma10[ma10.length - 1],
        ma20: ma20[ma20.length - 1],
        ma50: ma50[ma50.length - 1],
        rsi: rsi[rsi.length - 1],
        macd_line: macd.macd[macd.macd.length - 1],
        macd_signal: macd.signal[macd.signal.length - 1],
        macd_histogram: macd.histogram[macd.histogram.length - 1],
        bb_upper: bb.upper[bb.upper.length - 1],
        bb_middle: bb.middle[bb.middle.length - 1],
        bb_lower: bb.lower[bb.lower.length - 1],
        atr: atr[atr.length - 1],
        volume_ratio: volumeRatio,
        momentum: momentum,
        volatility: volatility,
        support: supportResistance.support,
        resistance: supportResistance.resistance
      }
    }
    
    // ML辅助函数（简化实现）
    const calculateSMA = (data, period) => {
      const result = []
      for (let i = period - 1; i < data.length; i++) {
        let sum = 0
        for (let j = 0; j < period; j++) {
          sum += data[i - j]
        }
        result.push(sum / period)
      }
      return result
    }
    
    const calculateMACD = (prices) => {
      const ema12 = calculateEMA(prices, 12)
      const ema26 = calculateEMA(prices, 26)
      const macd = ema12.map((val, i) => val - ema26[i])
      const signal = calculateEMA(macd, 9)
      const histogram = macd.map((val, i) => val - signal[i])
      
      return { macd, signal, histogram }
    }
    
    const calculateEMA = (data, period) => {
      const result = []
      const multiplier = 2 / (period + 1)
      result[0] = data[0]
      
      for (let i = 1; i < data.length; i++) {
        result[i] = (data[i] - result[i - 1]) * multiplier + result[i - 1]
      }
      return result
    }
    
    const calculateBB = (prices, period, stdDev) => {
      const sma = calculateSMA(prices, period)
      const upper = []
      const lower = []
      
      for (let i = 0; i < sma.length; i++) {
        const dataIndex = i + period - 1
        const slice = prices.slice(dataIndex - period + 1, dataIndex + 1)
        const variance = slice.reduce((sum, val) => sum + Math.pow(val - sma[i], 2), 0) / period
        const standardDev = Math.sqrt(variance)
        
        upper.push(sma[i] + standardDev * stdDev)
        lower.push(sma[i] - standardDev * stdDev)
      }
      
      return { upper, middle: sma, lower }
    }
    
    const calculateATR = (data, period) => {
      const trueRanges = []
      
      for (let i = 1; i < data.length; i++) {
        const high = data[i].high
        const low = data[i].low
        const prevClose = data[i - 1].close
        
        const tr = Math.max(
          high - low,
          Math.abs(high - prevClose),
          Math.abs(low - prevClose)
        )
        trueRanges.push(tr)
      }
      
      return calculateSMA(trueRanges, period)
    }
    
    const calculateVolatility = (prices, period) => {
      if (prices.length < period) return 0
      
      const returns = []
      for (let i = 1; i < prices.length; i++) {
        returns.push((prices[i] - prices[i - 1]) / prices[i - 1])
      }
      
      const recentReturns = returns.slice(-period)
      const mean = recentReturns.reduce((sum, val) => sum + val, 0) / recentReturns.length
      const variance = recentReturns.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / recentReturns.length
      
      return Math.sqrt(variance)
    }
    
    const calculateSupportResistance = (data) => {
      const period = Math.min(20, data.length)
      const recentData = data.slice(-period)
      
      const highs = recentData.map(d => d.high)
      const lows = recentData.map(d => d.low)
      
      const resistance = Math.max(...highs)
      const support = Math.min(...lows)
      
      return { support, resistance }
    }
    
    const calculateTrendSlope = (prices) => {
      if (prices.length < 2) return 0
      
      let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0
      const n = prices.length
      
      for (let i = 0; i < n; i++) {
        sumX += i
        sumY += prices[i]
        sumXY += i * prices[i]
        sumXX += i * i
      }
      
      const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX)
      return slope / (sumY / n) // 标准化斜率
    }
    
    const identifyMarketState = (data, index) => {
      const lookback = Math.min(50, index)
      const recentData = data.slice(index - lookback + 1, index + 1)
      const prices = recentData.map(d => d.close)
      
      const trendSlope = calculateTrendSlope(prices)
      const volatility = calculateVolatility(prices, Math.min(20, prices.length))
      
      if (Math.abs(trendSlope) < 0.001 && volatility < 0.02) {
        return 'sideways'
      } else if (trendSlope > 0.002) {
        return 'bull'
      } else if (trendSlope < -0.002) {
        return 'bear'
      } else {
        return 'neutral'
      }
    }
    
    // 优化：ML预测算法（增强版）
    const performMLPrediction = (features, marketState) => {
      const weights = getFeatureWeights(backtestSettings.mlFeatureWeighting)
      
      let buyScore = 0
      let sellScore = 0
      
      // 1. 趋势因子（增强版）
      const trendScore = calculateTrendScore(features)
      buyScore += trendScore.bullish * weights.trend
      sellScore += trendScore.bearish * weights.trend
      
      // 2. 动量因子（多层次）
      const momentumScore = calculateMomentumScore(features)
      buyScore += momentumScore.bullish * weights.momentum
      sellScore += momentumScore.bearish * weights.momentum
      
      // 3. 反转因子（精细化）
      const reversalScore = calculateReversalScore(features)
      buyScore += reversalScore.bullish * weights.reversal
      sellScore += reversalScore.bearish * weights.reversal
      
      // 4. 成交量因子（新增）
      const volumeScore = calculateVolumeScore(features)
      buyScore += volumeScore.bullish * weights.volume
      sellScore += volumeScore.bearish * weights.volume
      
      // 5. 波动性因子（新增）
      const volatilityScore = calculateVolatilityScore(features)
      buyScore += volatilityScore.adjustment
      sellScore -= volatilityScore.adjustment
      
      // 6. 市场状态调整（优化）
      const stateMultiplier = getMarketStateMultiplier(marketState, features)
      buyScore *= stateMultiplier.buy
      sellScore *= stateMultiplier.sell
      
      // 7. 情绪指标调整（增强）
      const sentimentFactor = calculateAdvancedSentimentIndicator(features, marketState)
      buyScore += sentimentFactor * backtestSettings.mlSentimentWeight
      sellScore -= sentimentFactor * backtestSettings.mlSentimentWeight
      
      // 8. 正则化评分（改进）
      const totalScore = Math.abs(buyScore) + Math.abs(sellScore)
      let normalizedBuyScore = totalScore > 0 ? Math.abs(buyScore) / totalScore : 0.5
      let normalizedSellScore = totalScore > 0 ? Math.abs(sellScore) / totalScore : 0.5
      
      // 9. 信号筛选和置信度计算
      let signal = 'hold'
      let confidence = 0
      
      const signalThreshold = 0.55 // 降低阈值提高灵敏度
      const strongSignalThreshold = 0.7 // 强信号阈值
      
      if (normalizedBuyScore > signalThreshold && normalizedBuyScore > normalizedSellScore) {
        signal = 'buy'
        confidence = normalizedBuyScore
        // 强信号额外加分
        if (normalizedBuyScore > strongSignalThreshold) {
          confidence = Math.min(0.95, confidence * 1.1)
        }
      } else if (normalizedSellScore > signalThreshold && normalizedSellScore > normalizedBuyScore) {
        signal = 'sell'
        confidence = normalizedSellScore
        // 强信号额外加分
        if (normalizedSellScore > strongSignalThreshold) {
          confidence = Math.min(0.95, confidence * 1.1)
        }
      }
      
      return {
        signal,
        confidence,
        buyScore: normalizedBuyScore,
        sellScore: normalizedSellScore,
        marketState,
        details: { // 新增：详细信息
          trendScore,
          momentumScore,
          reversalScore,
          volumeScore,
          volatilityScore,
          sentimentFactor
        }
      }
    }
    
    // 新增：趋势评分算法
    const calculateTrendScore = (features) => {
      let bullish = 0
      let bearish = 0
      
      // 多层MA分析
      const maAlignment = {
        short: features.price > features.ma5 ? 1 : -1,
        medium: features.ma5 > features.ma20 ? 1 : -1,
        long: features.ma20 > features.ma50 ? 1 : -1
      }
      
      // MA排列评分
      const alignmentScore = (maAlignment.short + maAlignment.medium + maAlignment.long) / 3
      if (alignmentScore > 0.33) bullish += 0.4
      if (alignmentScore < -0.33) bearish += 0.4
      
      // 价格位置分析
      const pricePosition = {
        aboveMA5: (features.price - features.ma5) / features.ma5,
        aboveMA20: (features.price - features.ma20) / features.ma20
      }
      
      if (pricePosition.aboveMA5 > 0.02) bullish += 0.3
      if (pricePosition.aboveMA5 < -0.02) bearish += 0.3
      if (pricePosition.aboveMA20 > 0.05) bullish += 0.3
      if (pricePosition.aboveMA20 < -0.05) bearish += 0.3
      
      return { bullish, bearish }
    }
    
    // 新增：动量评分算法
    const calculateMomentumScore = (features) => {
      let bullish = 0
      let bearish = 0
      
      // 价格动量
      if (features.momentum > 0.03) bullish += 0.5
      else if (features.momentum > 0.01) bullish += 0.3
      if (features.momentum < -0.03) bearish += 0.5
      else if (features.momentum < -0.01) bearish += 0.3
      
      // RSI动量
      if (features.rsi < 25) bullish += 0.4
      else if (features.rsi < 35) bullish += 0.2
      if (features.rsi > 75) bearish += 0.4
      else if (features.rsi > 65) bearish += 0.2
      
      // MACD动量
      if (features.macd_line > features.macd_signal && features.macd_histogram > 0) bullish += 0.3
      if (features.macd_line < features.macd_signal && features.macd_histogram < 0) bearish += 0.3
      
      // MACD金叉死叉加分
      const macdCrossover = features.macd_histogram > 0 && Math.abs(features.macd_histogram) > Math.abs(features.macd_line) * 0.1
      if (macdCrossover && features.macd_line > 0) bullish += 0.2
      if (!macdCrossover && features.macd_line < 0) bearish += 0.2
      
      return { bullish, bearish }
    }
    
    // 新增：反转评分算法
    const calculateReversalScore = (features) => {
      let bullish = 0
      let bearish = 0
      
      // 布林带位置
      const bbPosition = (features.price - features.bb_lower) / (features.bb_upper - features.bb_lower)
      if (bbPosition < 0.15) bullish += 0.6 // 接近下轨
      else if (bbPosition < 0.25) bullish += 0.3
      if (bbPosition > 0.85) bearish += 0.6 // 接近上轨
      else if (bbPosition > 0.75) bearish += 0.3
      
      // 支撑阻力分析
      const supportDistance = (features.price - features.support) / features.support
      const resistanceDistance = (features.resistance - features.price) / features.price
      
      if (supportDistance < 0.015) bullish += 0.4 // 靠近支撑
      if (resistanceDistance < 0.015) bearish += 0.4 // 靠近阻力
      
      // 极端指标值
      if (features.rsi < 15) bullish += 0.5 // 极度超卖
      if (features.rsi > 85) bearish += 0.5 // 极度超买
      
      return { bullish, bearish }
    }
    
    // 新增：成交量评分算法
    const calculateVolumeScore = (features) => {
      let bullish = 0
      let bearish = 0
      
      // 成交量放大程度
      if (features.volume_ratio > 2.5) {
        bullish += 0.4 // 大量放大通常是看涨信号
      } else if (features.volume_ratio > 1.8) {
        bullish += 0.2
      } else if (features.volume_ratio < 0.5) {
        bearish += 0.2 // 成交量萝缩可能是下跌信号
      }
      
      // 成交量与价格变化的关系
      if (features.volume_ratio > 1.5 && features.momentum > 0) {
        bullish += 0.3 // 量价齐升
      }
      
      if (features.volume_ratio > 1.5 && features.momentum < 0) {
        bearish += 0.3 // 量增价跌
      }
      
      return { bullish, bearish }
    }
    
    // 新增：波动性评分算法
    const calculateVolatilityScore = (features) => {
      let adjustment = 0
      
      // 波动性调整（低波动性适合交易，高波动性需谨慎）
      if (features.volatility < 0.015) {
        adjustment = 0.1 // 低波动性增加信心
      } else if (features.volatility > 0.08) {
        adjustment = -0.2 // 高波动性减少信心
      } else if (features.volatility > 0.05) {
        adjustment = -0.1
      }
      
      return { adjustment }
    }
    
    // 新增：市场状态乘数
    const getMarketStateMultiplier = (marketState, features) => {
      switch (marketState) {
        case 'bull':
          return { buy: 1.3, sell: 0.7 }
        case 'bear':
          return { buy: 0.6, sell: 1.4 }
        case 'sideways':
          // 震荡市适合反转交易
          return features.rsi < 30 || features.rsi > 70 ? 
            { buy: 1.1, sell: 1.1 } : { buy: 0.9, sell: 0.9 }
        default:
          return { buy: 1.0, sell: 1.0 }
      }
    }
    
    // 优化：高级情绪指标
    const calculateAdvancedSentimentIndicator = (features, marketState) => {
      let sentiment = 0
      
      // 1. 恐慌指数（VIX类似）
      const fearIndex = calculateFearIndex(features)
      if (fearIndex > 0.8) sentiment += 0.6 // 极度恐慌时反向买入
      else if (fearIndex > 0.6) sentiment += 0.3
      
      // 2. 贪婪指数
      const greedIndex = calculateGreedIndex(features)
      if (greedIndex > 0.8) sentiment -= 0.6 // 极度贪婪时谨慎
      else if (greedIndex > 0.6) sentiment -= 0.3
      
      // 3. 技术指标远离平衡
      const technicalExtreme = calculateTechnicalExtreme(features)
      sentiment += technicalExtreme * 0.4
      
      // 4. 市场状态调整
      if (marketState === 'bear' && sentiment > 0) {
        sentiment *= 1.2 // 熊市中的反转信号更强
      } else if (marketState === 'bull' && sentiment < 0) {
        sentiment *= 1.2 // 牛市中的顶部信号更强
      }
      
      return Math.max(-1, Math.min(1, sentiment))
    }
    
    // 恐慌指数计算
    const calculateFearIndex = (features) => {
      let fearScore = 0
      
      // RSI极低值
      if (features.rsi < 20) fearScore += 0.4
      else if (features.rsi < 30) fearScore += 0.2
      
      // 价格远低于布林带下轨
      if (features.price < features.bb_lower * 0.98) fearScore += 0.3
      
      // 高波动性环境
      if (features.volatility > 0.06) fearScore += 0.3
      
      return Math.min(1, fearScore)
    }
    
    // 贪婪指数计算
    const calculateGreedIndex = (features) => {
      let greedScore = 0
      
      // RSI极高值
      if (features.rsi > 80) greedScore += 0.4
      else if (features.rsi > 70) greedScore += 0.2
      
      // 价格远高于布林带上轨
      if (features.price > features.bb_upper * 1.02) greedScore += 0.3
      
      // 成交量异常放大
      if (features.volume_ratio > 3) greedScore += 0.3
      
      return Math.min(1, greedScore)
    }
    
    // 技术指标远离平衡
    const calculateTechnicalExtreme = (features) => {
      let extremeScore = 0
      
      // 多个指标同时超买/超卖
      const oversoldCount = [
        features.rsi < 25,
        features.price < features.bb_lower,
        features.momentum < -0.05
      ].filter(Boolean).length
      
      const overboughtCount = [
        features.rsi > 75,
        features.price > features.bb_upper,
        features.momentum > 0.05
      ].filter(Boolean).length
      
      if (oversoldCount >= 2) extremeScore += 0.5
      if (overboughtCount >= 2) extremeScore -= 0.5
      
      return extremeScore
    }
    
    // 保留原有的getFeatureWeights函数（并优化）
    const getFeatureWeights = (mode) => {
      switch (mode) {
        case 'trend_focused':
          return { trend: 0.5, momentum: 0.2, reversal: 0.2, volume: 0.1 }
        case 'momentum_focused':
          return { trend: 0.2, momentum: 0.5, reversal: 0.2, volume: 0.1 }
        case 'reversal_focused':
          return { trend: 0.2, momentum: 0.2, reversal: 0.5, volume: 0.1 }
        case 'balanced':
        default:
          return { trend: 0.3, momentum: 0.3, reversal: 0.3, volume: 0.1 }
      }
    }
    
    // 新增：风险评估函数
    const evaluateRiskConditions = (features, marketState, consecutiveLosses, cash, initialCapital) => {
      let allowBuy = true
      let forceSell = false
      
      // 1. 连续亏损风险控制
      if (consecutiveLosses >= 3) {
        allowBuy = false // 连续3次亏损后暂停交易
      }
      
      // 2. 资金水位风险控制
      const remainingCapitalRatio = cash / initialCapital
      if (remainingCapitalRatio < 0.3) {
        allowBuy = false // 资金低于30%暂停交易
      }
      
      // 3. 极端市场环境风险控制
      if (features.volatility > 0.1 && marketState === 'bear') {
        allowBuy = false // 高波动性熊市环境下不交易
        forceSell = true // 强制清仓
      }
      
      // 4. 技术指标极端值风险控制
      if (features.rsi > 90 || features.rsi < 10) {
        if (features.rsi > 90) forceSell = true
        if (features.rsi < 10) allowBuy = false // 极度超卖时谨慎交易
      }
      
      return { allowBuy, forceSell }
    }
    
    // 优化：动态仓位管理函数（考虑连续亏损）
    const calculateDynamicPosition = (features, prediction, basePercent, consecutiveLosses = 0) => {
      let positionMultiplier = 1
      
      // 基于置信度调整
      positionMultiplier *= prediction.confidence
      
      // 基于波动性调整
      if (features.volatility > 0.05) {
        positionMultiplier *= 0.6 // 更保守
      } else if (features.volatility < 0.02) {
        positionMultiplier *= 1.4 // 更激进
      }
      
      // 基于连续亏损调整
      if (consecutiveLosses > 0) {
        positionMultiplier *= Math.pow(0.8, consecutiveLosses) // 逐次减少仓位
      }
      
      // 基于市场状态调整
      if (features.volume_ratio > 2.0) {
        positionMultiplier *= 1.2 // 成交量放大时适度增加
      }
      
      return Math.max(3, Math.min(40, basePercent * positionMultiplier)) // 调整范围
    }
    
    const calculateAdaptiveStopLoss = (atr, multiplier) => {
      return atr * multiplier / 100
    }
    
    const calculateAdaptiveTakeProfit = (atr, confidence) => {
      const baseMultiplier = 2
      const confidenceMultiplier = confidence * 2
      return atr * (baseMultiplier + confidenceMultiplier) / 100
    }
    
    const checkMLStopConditions = (currentPrice, lastBuyPrice, adaptiveStopLoss, adaptiveTakeProfit) => {
      if (!lastBuyPrice) return false
      
      const stopLossPrice = lastBuyPrice * (1 - adaptiveStopLoss)
      const takeProfitPrice = lastBuyPrice * (1 + adaptiveTakeProfit)
      
      return currentPrice <= stopLossPrice || currentPrice >= takeProfitPrice
    }
    
    // 实时ML策略信号生成
    const generateRealTimeMLStrategy1Signal = (priceHistory) => {
      if (priceHistory.length < 50) return null
      
      // 将价格历史转换为数据格式
      const data = priceHistory.map(p => ({
        date: p.date,
        close: p.close,
        high: p.close * 1.01, // 模拟高价
        low: p.close * 0.99,  // 模拟低价
        volume: 1000 + Math.random() * 1000 // 模拟成交量
      }))
      
      const index = data.length - 1
      const features = calculateMLFeatures(data, index)
      
      if (!features) return null
      
      let marketState = 'neutral'
      if (backtestSettings.mlMarketStateAware) {
        marketState = identifyMarketState(data, index)
      }
      
      const mlPrediction = performMLPrediction(features, marketState)
      
      if (mlPrediction.signal === 'buy' && 
          mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
          virtualTradingResults.position === 0) {
        return { 
          type: 'buy', 
          reason: `ML买入信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState})` 
        }
      }
      
      if (mlPrediction.signal === 'sell' && 
          mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
          virtualTradingResults.position > 0) {
        return { 
          type: 'sell', 
          reason: `ML卖出信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState})` 
        }
      }
      
      // 检查智能止损止盈
      if (virtualTradingResults.position > 0) {
        const lastBuyTrade = virtualTradingResults.trades.filter(t => t.type === 'buy').pop()
        if (lastBuyTrade) {
          const adaptiveStopLoss = calculateAdaptiveStopLoss(features.atr, backtestSettings.mlAdaptiveStopLoss)
          const adaptiveTakeProfit = calculateAdaptiveTakeProfit(features.atr, mlPrediction.confidence)
          
          if (checkMLStopConditions(features.price, lastBuyTrade.price, adaptiveStopLoss, adaptiveTakeProfit)) {
            return { 
              type: 'sell', 
              reason: `智能止损止盈(ATR:${features.atr.toFixed(2)})` 
            }
          }
        }
      }
      
      return null
    }
    
    // 历史数据ML策略信号生成
    const generateMLStrategy1Signal = (data, currentIndex) => {
      const features = calculateMLFeatures(data, currentIndex)
      if (!features) return null
      
      let marketState = 'neutral'
      if (backtestSettings.mlMarketStateAware) {
        marketState = identifyMarketState(data, currentIndex)
      }
      
      const mlPrediction = performMLPrediction(features, marketState)
      
      if (mlPrediction.signal === 'buy' && 
          mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
          virtualTradingResults.position === 0) {
        return { 
          type: 'buy', 
          reason: `ML买入信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState})` 
        }
      }
      
      if (mlPrediction.signal === 'sell' && 
          mlPrediction.confidence >= backtestSettings.mlConfidenceThreshold && 
          virtualTradingResults.position > 0) {
        return { 
          type: 'sell', 
          reason: `ML卖出信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState})` 
        }
      }
      
      return null
    }
    
    // 计算回测结果
    const calculateBacktestResults = () => {
      if (!backtestResults.value || !backtestResults.value.equityCurve || !backtestResults.value.equityCurve.length) return
      
      const equityCurve = backtestResults.value.equityCurve
      const trades = backtestResults.value.trades
      
      // 计算总收益率
      const initialEquity = equityCurve[0].equity
      const finalEquity = equityCurve[equityCurve.length - 1].equity
      backtestSummary.totalReturn = ((finalEquity - initialEquity) / initialEquity) * 100
      
      // 计算年化收益率
      const days = equityCurve.length
      const years = days / 365
      backtestSummary.annualReturn = years > 0 ? (Math.pow(1 + backtestSummary.totalReturn / 100, 1 / years) - 1) * 100 : 0
      
      // 计算夏普比率
      const returns = []
      for (let i = 1; i < equityCurve.length; i++) {
        const ret = (equityCurve[i].equity - equityCurve[i - 1].equity) / equityCurve[i - 1].equity
        returns.push(ret)
      }
      
      const avgReturn = returns.length > 0 ? returns.reduce((a, b) => a + b, 0) / returns.length : 0
      const stdDev = returns.length > 1 ? Math.sqrt(returns.map(x => Math.pow(x - avgReturn, 2)).reduce((a, b) => a + b, 0) / returns.length) : 0
      backtestSummary.sharpeRatio = stdDev === 0 ? 0 : avgReturn / stdDev
      
      // 计算最大回撤
      let peak = initialEquity
      let maxDrawdown = 0
      
      for (const item of equityCurve) {
        if (item.equity > peak) peak = item.equity
        const drawdown = (peak - item.equity) / peak
        if (drawdown > maxDrawdown) maxDrawdown = drawdown
      }
      
      backtestSummary.maxDrawdown = maxDrawdown * 100
      
      // 计算胜率
      const profitableTrades = trades.filter(t => t.profit && t.profit > 0).length
      backtestSummary.totalTrades = trades.filter(t => t.profit !== undefined).length
      backtestSummary.winRate = backtestSummary.totalTrades > 0 ? (profitableTrades / backtestSummary.totalTrades) * 100 : 0
    }
    
    // 绘制回测结果图表
    const drawBacktestChart = (results) => {
      if (!backtestChart.value || !results || !results.equityCurve || !results.equityCurve.length) {
        console.warn('图表容器或数据不存在')
        return
      }
      
      // 销毁旧图表实例
      if (backtestChartInstance.value) {
        backtestChartInstance.value.dispose()
        backtestChartInstance.value = null
      }
      
      // 初始化图表
      backtestChartInstance.value = echarts.init(backtestChart.value)
      
      // 准备图表数据
      const dates = results.equityCurve.map(item => item.date)
      const equityValues = results.equityCurve.map(item => item.equity)
      
      const option = {
        title: {
          text: '回测结果 - 权益曲线',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const date = params[0].axisValue
            const value = params[0].data.toFixed(2)
            return `${date}<br/>权益: $${value}`
          }
        },
        xAxis: {
          type: 'category',
          data: dates,
          scale: true,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          axisLabel: {
            formatter: function(value) {
              return value.split(' ')[0] // 只显示日期部分
            }
          }
        },
        yAxis: {
          type: 'value',
          scale: true,
          splitLine: { show: true },
          axisLabel: {
            formatter: '${value}'
          }
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '3%',
          containLabel: true
        },
        series: [
          {
            name: '权益',
            type: 'line',
            data: equityValues,
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 2,
              color: '#5470c6'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(84, 112, 198, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(84, 112, 198, 0.1)'
                }
              ])
            }
          }
        ]
      }
      
      backtestChartInstance.value.setOption(option)
      
      // 响应窗口大小变化
      const resizeHandler = () => {
        if (backtestChartInstance.value) {
          backtestChartInstance.value.resize()
        }
      }
      window.addEventListener('resize', resizeHandler)
    }
    
    // 保存策略
    const saveStrategy = () => {
      if (!backtestResults.value.equityCurve || !backtestResults.value.equityCurve.length) {
        ElMessage({
          message: '请先运行回测',
          type: 'warning'
        })
        return
      }
      
      ElMessageBox.prompt('请输入策略名称', '保存策略', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '策略名称不能为空'
      }).then(({ value }) => {
        // 保存策略到本地存储
        const savedStrategies = JSON.parse(localStorage.getItem('backtestStrategies') || '[]')
        
        const strategyToSave = {
          id: Date.now(),
          name: value,
          settings: { ...backtestSettings },
          summary: { ...backtestSummary },
          savedAt: new Date().toLocaleString()
        }
        
        savedStrategies.push(strategyToSave)
        localStorage.setItem('backtestStrategies', JSON.stringify(savedStrategies))
        
        ElMessage({
          message: `策略 "${value}" 已保存`,
          type: 'success'
        })
      }).catch(() => {
        // 取消保存
      })
    }
    
    // 加载策略
    const loadStrategy = () => {
      // 从本地存储获取已保存的策略
      const savedStrategies = JSON.parse(localStorage.getItem('backtestStrategies') || '[]')
      
      if (savedStrategies.length === 0) {
        ElMessage({
          message: '没有找到已保存的策略',
          type: 'info'
        })
        return
      }
      
      // 准备策略列表
      const options = savedStrategies.map(strategy => ({
        label: `${strategy.name} (${strategy.savedAt}) - 收益率: ${strategy.summary.totalReturn.toFixed(2)}%`,
        value: strategy.id
      }))
      
      // 显示策略选择对话框
      ElMessageBox.select('选择要加载的策略', '加载策略', options, {
        confirmButtonText: '加载',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        // 查找选中的策略
        const selectedStrategy = savedStrategies.find(s => s.id === value)
        
        if (selectedStrategy) {
          // 加载策略设置
          Object.assign(backtestSettings, selectedStrategy.settings)
          
          ElMessage({
            message: `策略 "${selectedStrategy.name}" 已加载`,
            type: 'success'
          })
          
          // 清空当前回测结果
          backtestResults.value = { equityCurve: [], trades: [] }
          backtestTrades.value = []
          
          // 如果有图表实例，清除图表
          if (backtestChartInstance.value) {
            backtestChartInstance.value.clear()
          }
        }
      }).catch(() => {
        // 取消加载
      })
    }
    
    // 新增：策略性能分析函数
    const calculateStrategyPerformance = (results) => {
      const trades = results.trades || []
      const signals = results.signals || []
      const equityCurve = results.equityCurve || []
      
      if (trades.length === 0) return {}
      
      // 信号质量分析
      const signalQuality = {
        totalSignals: signals.length,
        avgConfidence: signals.length > 0 ? signals.reduce((sum, s) => sum + (s.confidence || 0), 0) / signals.length : 0,
        strongSignals: signals.filter(s => s.confidence > 0.8).length,
        weakSignals: signals.filter(s => s.confidence < 0.6).length
      }
      
      // 交易效率分析
      const sellTrades = trades.filter(t => t.type === 'sell' && t.profit !== undefined)
      const profitableTrades = sellTrades.filter(t => t.profit > 0)
      
      const efficiency = {
        signalToTradeRatio: trades.length / Math.max(signals.length, 1),
        profitableTradeRatio: profitableTrades.length / Math.max(sellTrades.length, 1),
        avgHoldingPeriod: calculateAvgHoldingPeriod(trades),
        maxConsecutiveWins: calculateMaxConsecutive(sellTrades, true),
        maxConsecutiveLosses: calculateMaxConsecutive(sellTrades, false)
      }
      
      // 风险指标
      const riskMetrics = {
        maxDrawdown: calculateMaxDrawdownFromCurve(equityCurve),
        volatility: calculateEquityVolatility(equityCurve),
        riskAdjustedReturn: calculateRiskAdjustedReturn(equityCurve)
      }
      
      return {
        signalQuality,
        efficiency,
        riskMetrics,
        recommendation: generateStrategyRecommendation(signalQuality, efficiency, riskMetrics)
      }
    }
    
    // 辅助函数
    const calculateAvgHoldingPeriod = (trades) => {
      const pairs = []
      let buyTrade = null
      
      for (const trade of trades) {
        if (trade.type === 'buy') {
          buyTrade = trade
        } else if (trade.type === 'sell' && buyTrade) {
          const buyDate = new Date(buyTrade.date)
          const sellDate = new Date(trade.date)
          pairs.push((sellDate - buyDate) / (1000 * 60 * 60 * 24)) // 天数
          buyTrade = null
        }
      }
      
      return pairs.length > 0 ? pairs.reduce((a, b) => a + b, 0) / pairs.length : 0
    }
    
    const calculateMaxConsecutive = (trades, isWin) => {
      let maxCount = 0
      let currentCount = 0
      
      for (const trade of trades) {
        const condition = isWin ? trade.profit > 0 : trade.profit <= 0
        if (condition) {
          currentCount++
          maxCount = Math.max(maxCount, currentCount)
        } else {
          currentCount = 0
        }
      }
      
      return maxCount
    }
    
    const calculateMaxDrawdownFromCurve = (equityCurve) => {
      if (equityCurve.length === 0) return 0
      
      let maxEquity = equityCurve[0].equity
      let maxDrawdown = 0
      
      for (const point of equityCurve) {
        maxEquity = Math.max(maxEquity, point.equity)
        const drawdown = (maxEquity - point.equity) / maxEquity
        maxDrawdown = Math.max(maxDrawdown, drawdown)
      }
      
      return maxDrawdown * 100
    }
    
    const calculateEquityVolatility = (equityCurve) => {
      if (equityCurve.length < 2) return 0
      
      const returns = []
      for (let i = 1; i < equityCurve.length; i++) {
        const ret = (equityCurve[i].equity - equityCurve[i-1].equity) / equityCurve[i-1].equity
        returns.push(ret)
      }
      
      const mean = returns.reduce((a, b) => a + b, 0) / returns.length
      const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length
      
      return Math.sqrt(variance) * 100
    }
    
    const calculateRiskAdjustedReturn = (equityCurve) => {
      if (equityCurve.length === 0) return 0
      
      const totalReturn = (equityCurve[equityCurve.length - 1].equity - equityCurve[0].equity) / equityCurve[0].equity
      const volatility = calculateEquityVolatility(equityCurve) / 100
      
      return volatility > 0 ? totalReturn / volatility : 0
    }
    
    const generateStrategyRecommendation = (signalQuality, efficiency, riskMetrics) => {
      const recommendations = []
      
      // 信号质量建议
      if (signalQuality.avgConfidence < 0.7) {
        recommendations.push('建议提高置信度阈值或调整特征权重')
      }
      
      if (signalQuality.totalSignals > 0 && signalQuality.weakSignals / signalQuality.totalSignals > 0.4) {
        recommendations.push('弱信号过多，考虑开启风险过滤器')
      }
      
      // 交易效率建议
      if (efficiency.profitableTradeRatio < 0.5) {
        recommendations.push('胜率较低，建议优化止损止盈参数')
      }
      
      if (efficiency.maxConsecutiveLosses > 5) {
        recommendations.push('连续亏损过多，建议开启动态仓位管理')
      }
      
      // 风险控制建议
      if (riskMetrics.maxDrawdown > 20) {
        recommendations.push('最大回撤过大，建议降低仓位或加强风险控制')
      }
      
      if (riskMetrics.volatility > 15) {
        recommendations.push('策略波动性较大，建议调整情绪指标权重')
      }
      
      return recommendations.length > 0 ? recommendations : ['策略表现良好，可继续使用']
    }


    
    return {
      // 数据源相关
      dataSources,
      selectedDataSource,
      isLoading,
      lastUpdated,
      fetchDataBySource,
      fetchAllDataSources,
      autoRefresh,
      toggleAutoRefresh,
      
      // 市场数据
      marketOverview,
      symbols,
      selectedSymbol,
      binanceSymbol,
      binanceWebview,
      binanceCurrentPrice,
      updateBinanceChart,
      startBinancePriceMonitoring,
      stopBinancePriceMonitoring,
      
      // OKX 数据
      okxSymbol,
      okxWebview,
      okxCurrentPrice,
      updateOKXChart,
      startOKXPriceMonitoring,
      stopOKXPriceMonitoring,
      
      // 搬砖套利数据
      arbitrageSymbol,
      isArbitrageMonitoring,
      arbitrageOpportunity,
      binanceArbitragePrice,
      okxArbitragePrice,
      binanceChange,
      okxChange,
      arbitrageSpread,
      arbitrageValue,
      arbitrageFee,
      arbitrageHistory,
      arbitrageThreshold,
      tradeAmount,
      arbitrageUpdateInterval,
      arbitrageFeeRate,
      arbitrageStats,
      formatDuration,
      updateArbitrageData,
      startArbitrageMonitoring,
      changeUpdateInterval,
      exportArbitrageHistory,
      clearArbitrageHistory
    }
  }
}
</script>

<style scoped>
.market-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.market-price {
  font-size: 18px;
  font-weight: bold;
}

.exchange-price {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.market-change {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
}

.up {
  color: #14b143;
}

.down {
  color: #ef232a;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.trading-chart {
  width: 100%;
  height: 100%;
}

.binance-webview {
  width: 100%;
  height: 700px;
  border: none;
  display: inline-flex;
}

.buy-btn {
  background-color: #14b143;
  border-color: #14b143;
}

.sell-btn {
  background-color: #ef232a;
  border-color: #ef232a;
}

.asset-overview {
  padding: 10px 0;
}

.asset-item {
  text-align: center;
  margin-bottom: 10px;
}

.asset-label {
  font-size: 14px;
  color: #909399;
}

.asset-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.asset-detail {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 5px 0;
}

.asset-name {
  font-weight: bold;
}

.asset-balance {
  color: #606266;
}

.data-source-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.last-updated {
  font-size: 12px;
  color: #909399;
  margin-right: 10px;
}

.price-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.price-cell div:first-child {
  font-weight: bold;
  margin-bottom: 4px;
}

.price-diff .warning {
  color: #e6a23c;
  font-weight: bold;
}

.up {
  color: #14b143;
}

.down {
  color: #ef232a;
}

/* 虚拟交易相关样式 */
.virtual-stat-item {
  text-align: center;
  padding: 10px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #fde68a;
}

.virtual-stat-item .stat-label {
  font-size: 12px;
}

.param-setting {
  text-align: center;
}

.param-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
}

.param-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.arbitrage-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.arbitrage-spread, .arbitrage-value, .arbitrage-fee, .arbitrage-profit {
  font-size: 14px;
  padding: 5px 0;
}

.arbitrage-profit.profit {
  color: #14b143;
  font-weight: bold;
}

.arbitrage-profit.loss {
  color: #ef232a;
  font-weight: bold;
}

.exchange-card {
  text-align: center;
}

.exchange-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.exchange-price {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.exchange-change {
  font-size: 14px;
}

/* 统计卡片样式 */
.stat-card {
  background: #ffffff;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  height: 100%;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-number {
  font-size: 18px;
  font-weight: bold;
  color: #1e293b;
  margin-bottom: 4px;
  line-height: 1.2;
}

.stat-detail {
  font-size: 11px;
  color: #94a3b8;
  line-height: 1.3;
}

.stat-number.neutral {
  color: #f59e0b;
}

.arbitrage-timer {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}
</style>